<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     * Optimized for handling 1000+ orders daily from 5-10 stores
     */
    public function up(): void
    {
        // Most indexes already exist, only add what's missing

        // Drop old idx_orders_order_number and make it unique
        try {
            DB::statement('ALTER TABLE orders DROP INDEX idx_orders_order_number');
        } catch (\Exception $e) {
            // Doesn't exist, continue
        }

        try {
            Schema::table('orders', function (Blueprint $table) {
                $table->unique('order_number', 'orders_order_number_unique');
            });
        } catch (\Exception $e) {
            // Already exists
        }

        // System settings index
        try {
            Schema::table('system_settings', function (Blueprint $table) {
                $table->index('key');
            });
        } catch (\Exception $e) {
            // Already exists
        }

        // Add only missing indexes (check if they exist first)
        // These are less critical, database already has good index coverage
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        try {
            Schema::table('orders', function (Blueprint $table) {
                $table->dropUnique('orders_order_number_unique');
            });
        } catch (\Exception $e) {
            // Doesn't exist
        }

        try {
            Schema::table('system_settings', function (Blueprint $table) {
                $table->dropIndex(['key']);
            });
        } catch (\Exception $e) {
            // Doesn't exist
        }
    }
};
