<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        // Remove duplicates - keep only the first occurrence
        DB::statement("
            DELETE t1 FROM products t1
            INNER JOIN products t2 
            WHERE t1.id > t2.id 
            AND t1.restaurant_id = t2.restaurant_id 
            AND t1.name = t2.name
        ");
        
        Schema::table('products', function (Blueprint $table) {
            $table->unique(['restaurant_id', 'name'], 'unique_restaurant_product');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('products', function (Blueprint $table) {
            $table->dropUnique('unique_restaurant_product');
        });
    }
};
