<?php

declare(strict_types=1);

namespace App\Domain\PreSave\Migrations;

use App\Framework\Database\ConnectionInterface;
use App\Framework\Database\Migration\Migration;
use App\Framework\Database\Migration\MigrationVersion;
use App\Framework\Database\Schema\Blueprint;
use App\Framework\Database\Schema\ForeignKeyAction;
use App\Framework\Database\Schema\Schema;

/**
 * Create Pre-Save Registrations Table
 */
final class CreatePresaveRegistrationsTable implements Migration
{
    public function up(ConnectionInterface $connection): void
    {
        $schema = new Schema($connection);

        $schema->createIfNotExists('presave_registrations', function (Blueprint $table) {
            $table->id();
            $table->bigInteger('campaign_id'); // Match the signed BIGINT type of presave_campaigns.id
            $table->string('user_id', 255);
            $table->string('platform', 50);
            $table->string('status', 20)->default('pending');
            $table->bigInteger('registered_at');
            $table->bigInteger('processed_at')->nullable();
            $table->text('error_message')->nullable();
            $table->unsignedInteger('retry_count')->default(0);

            // Unique constraint
            $table->unique(['campaign_id', 'user_id', 'platform']);

            // Foreign key
            $table->foreign('campaign_id')
                  ->references('id')
                  ->on('presave_campaigns')
                  ->onDelete(ForeignKeyAction::CASCADE);

            // Indexes
            $table->index(['campaign_id']);
            $table->index(['user_id']);
            $table->index(['status']);
            $table->index(['platform']);
        });

        $schema->execute();
    }

    public function down(ConnectionInterface $connection): void
    {
        $schema = new Schema($connection);
        $schema->dropIfExists('presave_registrations');
        $schema->execute();
    }

    public function getVersion(): MigrationVersion
    {
        return MigrationVersion::fromTimestamp("2025_01_10_150001");
    }

    public function getDescription(): string
    {
        return "Create pre-save registrations table";
    }
}
