<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * Catatan: migrasi ini idempoten. Pada instalasi baru, index unik
     * `order_no` sudah diubah menjadi index biasa oleh migrasi sebelumnya
     * (110000_drop_unique_order_no_from_sales_table), sehingga di sini kita
     * hanya bertindak bila index unik masih ada.
     */
    public function up(): void
    {
        if ($this->indexExists('sales', 'sales_order_no_unique')) {
            Schema::table('sales', function ($table) {
                $table->dropUnique(['order_no']);
            });
        }

        if (! $this->indexExists('sales', 'sales_order_no_index')) {
            Schema::table('sales', function ($table) {
                $table->index('order_no');
            });
        }
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        if ($this->indexExists('sales', 'sales_order_no_index')) {
            Schema::table('sales', function ($table) {
                $table->dropIndex(['order_no']);
            });
        }

        if (! $this->indexExists('sales', 'sales_order_no_unique')) {
            Schema::table('sales', function ($table) {
                $table->unique('order_no');
            });
        }
    }

    private function indexExists(string $table, string $index): bool
    {
        if (DB::getDriverName() === 'sqlite') {
            // For SQLite, use pragma index_list
            $result = DB::selectOne("PRAGMA index_list({$table})");
            if ($result === null) {
                return false;
            }
            // Get all indexes for the table
            $indexes = DB::select("PRAGMA index_list({$table})");
            foreach ($indexes as $idx) {
                if ($idx->name === $index) {
                    return true;
                }
            }
            return false;
        }

        // For MySQL/PostgreSQL
        return DB::table('information_schema.statistics')
            ->where('table_schema', DB::raw('DATABASE()'))
            ->where('table_name', $table)
            ->where('index_name', $index)
            ->exists();
    }
};
