<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * FIX: Prevent orders from being deleted when a store is removed.
     *
     * PROBLEM: The original migration had onDelete('cascade') which deletes
     * ALL orders when a store is deleted. This is wrong because:
     * - Checkout orders (CK-) are NOT related to stores
     * - Sales page orders (SP-) are NOT related to stores
     * - WooCommerce orders should be preserved for historical data
     *
     * SOLUTION: Change cascade delete to SET NULL, so orders are preserved
     * and only the store_id reference is removed.
     */
    public function up(): void
    {
        Schema::table('orders', function (Blueprint $table) {
            // Drop the old foreign key with CASCADE DELETE
            $table->dropForeign(['store_id']);

            // Add new foreign key with SET NULL (preserves orders, removes store reference)
            $table->foreign('store_id')
                  ->references('id')
                  ->on('stores')
                  ->onDelete('set null');  // When store deleted, set store_id to NULL (preserve order!)
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('orders', function (Blueprint $table) {
            // Drop the SET NULL foreign key
            $table->dropForeign(['store_id']);

            // Restore the old CASCADE DELETE (not recommended, but for rollback)
            $table->foreign('store_id')
                  ->references('id')
                  ->on('stores')
                  ->onDelete('cascade');
        });
    }
};
