<?php

declare(strict_types=1);

namespace App\Domain\Media\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\Schema;

final readonly class UpdateImageVariantsConstraint implements Migration
{
    public function up(ConnectionInterface $connection): void
    {
        $schema = new Schema($connection);

        // Drop existing constraint
        $schema->table('image_variants', function (Blueprint $table) {
            $table->dropUnique('uk_image_variants_combination');
        });

        $schema->execute();

        // Add new constraint with size column
        $schema = new Schema($connection);
        $schema->table('image_variants', function (Blueprint $table) {
            $table->unique(['image_id', 'variant_type', 'size', 'format'], 'uk_image_variants_combination');
        });

        $schema->execute();
    }

    public function down(ConnectionInterface $connection): void
    {
        $schema = new Schema($connection);

        // Drop current constraint
        $schema->table('image_variants', function (Blueprint $table) {
            $table->dropUnique('uk_image_variants_combination');
        });

        $schema->execute();

        // Restore original constraint
        $schema = new Schema($connection);
        $schema->table('image_variants', function (Blueprint $table) {
            $table->unique(['image_id', 'variant_type', 'format'], 'uk_image_variants_combination');
        });

        $schema->execute();
    }

    public function getVersion(): MigrationVersion
    {
        return MigrationVersion::fromTimestamp("2024_01_18_000006");
    }

    public function getDescription(): string
    {
        return "Update unique constraint to include size column";
    }
}
