<?php

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

/**
 * Consolidate onto artwork_favourites.
 *
 * Any rows in the interim user_favorites table (created 2026-02-07) that are
 * not already present in artwork_favourites are copied over, then
 * user_favorites is dropped so only one favourites table remains.
 */
return new class extends Migration
{
    public function up(): void
    {
        if (! Schema::hasTable('user_favorites')) {
            return;
        }

        // Copy any rows not yet in artwork_favourites, using insertOrIgnore so the
        // unique (user_id, artwork_id) constraint silently skips duplicates.
        // chunk() avoids memory spikes on large tables.
        DB::table('user_favorites')->orderBy('id')->chunk(500, function ($rows) {
            DB::table('artwork_favourites')->insertOrIgnore(
                $rows->map(fn ($r) => [
                    'user_id'    => $r->user_id,
                    'artwork_id' => $r->artwork_id,
                    'created_at' => $r->created_at,
                    'updated_at' => $r->created_at,
                ])->all()
            );
        });

        Schema::drop('user_favorites');
    }

    public function down(): void
    {
        if (Schema::hasTable('user_favorites')) {
            return;
        }

        Schema::create('user_favorites', function ($table) {
            $table->id();
            $table->unsignedBigInteger('user_id');
            $table->unsignedBigInteger('artwork_id');
            $table->timestamp('created_at')->nullable();
            $table->unique(['user_id', 'artwork_id']);
        });
    }
};
