<?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 productsizes table with proper constraints
        Schema::dropIfExists('productsizes');
        
        Schema::create('productsizes', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('product_id');
            $table->unsignedBigInteger('size_id');
            $table->timestamps();
            
            // Add proper foreign key constraints
            $table->foreign('product_id')
                  ->references('id')
                  ->on('products')
                  ->onDelete('cascade')
                  ->onUpdate('cascade');
            
            $table->foreign('size_id')
                  ->references('id')
                  ->on('sizes')
                  ->onDelete('cascade')
                  ->onUpdate('cascade');
            
            // Add unique constraint to prevent duplicate entries
            $table->unique(['product_id', 'size_id']);
        });
    }

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