<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        // Drop and recreate the productcolors table with proper constraints
        Schema::dropIfExists('productcolors');
        
        Schema::create('productcolors', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('product_id');
            $table->unsignedBigInteger('color_id');
            $table->timestamps();
            
            // Add proper foreign key constraints
            $table->foreign('product_id')
                  ->references('id')
                  ->on('products')
                  ->onDelete('cascade')
                  ->onUpdate('cascade');
            
            $table->foreign('color_id')
                  ->references('id')
                  ->on('colors')
                  ->onDelete('cascade')
                  ->onUpdate('cascade');
            
            // Add unique constraint to prevent duplicate entries
            $table->unique(['product_id', 'color_id']);
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('productcolors');
        
        // Recreate the old table structure if migration is rolled back
        Schema::create('productcolors', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('product_id');
            $table->integer('color_id');
            $table->timestamps();
        });
    }
};
