<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('sync_outboxes', function (Blueprint $table) {
            $table->id();
            $table->uuid('event_uuid')->unique();
            $table->string('origin_server_code', 50)->index();
            $table->unsignedInteger('farm_id')->nullable()->index();
            $table->string('aggregate_type', 80)->index();
            $table->uuid('aggregate_uuid')->index();
            $table->string('action', 30);
            $table->json('payload');
            $table->char('data_hash', 64)->nullable();
            $table->string('status', 30)->default('pending')->index();
            $table->unsignedSmallInteger('attempts')->default(0);
            $table->timestamp('available_at')->nullable()->index();
            $table->timestamp('last_attempt_at')->nullable();
            $table->timestamp('synced_at')->nullable();
            $table->json('cloud_response')->nullable();
            $table->text('last_error')->nullable();
            $table->timestamps();

            $table->index(['status', 'available_at']);
            $table->index(['aggregate_type', 'aggregate_uuid']);
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('sync_outboxes');
    }
};
