<?php

declare(strict_types=1);

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

return new class extends Migration {
    public function up(): void
    {
        if (Schema::hasTable('artwork_relations')) {
            return;
        }

        Schema::create('artwork_relations', function (Blueprint $table): void {
            $table->id();
            $table->foreignId('source_artwork_id')->constrained('artworks')->cascadeOnDelete();
            $table->foreignId('target_artwork_id')->constrained('artworks')->cascadeOnDelete();
            $table->string('relation_type', 32)->default('remake_of')->index();
            $table->text('note')->nullable();
            $table->unsignedSmallInteger('sort_order')->default(0);
            $table->foreignId('created_by_user_id')->nullable()->constrained('users')->nullOnDelete();
            $table->timestamps();

            $table->unique([
                'source_artwork_id',
                'target_artwork_id',
                'relation_type',
            ], 'artwork_relations_unique_pair_type');
            $table->index(['source_artwork_id', 'sort_order'], 'artwork_relations_source_sort_idx');
            $table->index(['target_artwork_id', 'relation_type'], 'artwork_relations_target_type_idx');
        });
    }

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