<?php

declare(strict_types=1);

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
    {
        // 1. Add is_active status column to modifiers table
        if (!Schema::hasColumn('modifiers', 'is_active')) {
            Schema::table('modifiers', function (Blueprint $table) {
                $table->boolean('is_active')->default(true)->after('usage_qty');
            });
        }

        // 2. Create product_modifiers pivot table
        Schema::create('product_modifiers', function (Blueprint $table) {
            $table->foreignId('product_id')->constrained('products')->onDelete('cascade');
            $table->foreignId('modifier_id')->constrained('modifiers')->onDelete('cascade');
            $table->primary(['product_id', 'modifier_id']);
        });

        // 3. For backward compatibility, map all existing modifiers to all existing products
        try {
            $productIds = DB::table('products')->pluck('id');
            $modifierIds = DB::table('modifiers')->pluck('id');

            $pivotData = [];
            foreach ($productIds as $pId) {
                foreach ($modifierIds as $mId) {
                    $pivotData[] = [
                        'product_id' => $pId,
                        'modifier_id' => $mId,
                    ];
                }
            }

            if (!empty($pivotData)) {
                DB::table('product_modifiers')->insertOrIgnore($pivotData);
            }
        } catch (\Exception $e) {
            // Keep going if table is empty or fails
        }
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('product_modifiers');

        if (Schema::hasColumn('modifiers', 'is_active')) {
            Schema::table('modifiers', function (Blueprint $table) {
                $table->dropColumn('is_active');
            });
        }
    }
};
