<?php

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

/**
 * Modernized replacement for the legacy `favourites` table.
 *
 * What changed from the legacy schema:
 *   - Renamed table: favourites → artwork_favourites
 *   - `favourite_id`  → `id`  (bigint unsigned, auto-increment)
 *   - `datum`         → `created_at` / `updated_at` via timestamps()
 *   - `user_type`     dropped — membership tier is not a property of the
 *                     favourite relationship; query via users.role if needed
 *   - `author_id`     dropped — always derivable via artworks.user_id
 *   - Both FKs are constrained with cascadeOnDelete so orphaned rows are
 *     automatically cleaned up when an artwork or user is hard-deleted
 *   - `legacy_id` tracks the original favourite_id for idempotent re-imports
 */
return new class extends Migration
{
    public function up(): void
    {
        Schema::create('artwork_favourites', function (Blueprint $table): void {
            $table->id();

            $table->foreignId('user_id')
                  ->constrained('users')
                  ->cascadeOnDelete();

            $table->foreignId('artwork_id')
                  ->constrained('artworks')
                  ->cascadeOnDelete();

            // Preserve original legacy PK for idempotent re-imports.
            // NULL for favourites created natively in the new system.
            $table->unsignedInteger('legacy_id')->nullable()->unique();

            $table->timestamps();

            // Prevent duplicate favourites
            $table->unique(['user_id', 'artwork_id'], 'artwork_favourites_unique_user_artwork');

            // Fast lookup: "how many favourites does this artwork have?"
            $table->index('artwork_id');
            // Fast lookup: "which artworks has this user favourited?"
            $table->index('user_id');
        });
    }

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