<?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('artwork_similarities', function (Blueprint $table): void {
            $table->id();
            $table->foreignId('artwork_id')->constrained('artworks')->cascadeOnDelete();
            $table->foreignId('similar_artwork_id')->constrained('artworks')->cascadeOnDelete();
            $table->string('model', 64);
            $table->string('model_version', 64);
            $table->string('algo_version', 64)->default('clip-cosine-v1');
            $table->unsignedSmallInteger('rank');
            $table->decimal('score', 10, 7);
            $table->timestamp('generated_at')->nullable()->index();
            $table->json('meta')->nullable();
            $table->timestamps();

            $table->unique(['artwork_id', 'similar_artwork_id', 'algo_version'], 'artwork_similarities_unique_pair_algo');
            $table->index(['artwork_id', 'algo_version', 'rank', 'score'], 'artwork_similarities_page_read_idx');
            $table->index(['similar_artwork_id', 'algo_version'], 'artwork_similarities_reverse_idx');
        });
    }

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