<?php

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

return new class extends Migration
{
    public function up(): void
    {
        if (Schema::hasTable('ticket_items') && ! $this->hasIndex('ticket_items', 'idx_ticket_items_order_id')) {
            Schema::table('ticket_items', function (Blueprint $table): void {
                $table->index('order_id', 'idx_ticket_items_order_id');
            });
        }

        if (Schema::hasTable('settlement_batches') && ! $this->hasIndex('settlement_batches', 'idx_settlement_batches_result_batch_id')) {
            Schema::table('settlement_batches', function (Blueprint $table): void {
                $table->index('result_batch_id', 'idx_settlement_batches_result_batch_id');
            });
        }
    }

    public function down(): void
    {
        if (Schema::hasTable('settlement_batches') && $this->hasIndex('settlement_batches', 'idx_settlement_batches_result_batch_id')) {
            Schema::table('settlement_batches', function (Blueprint $table): void {
                $table->dropIndex('idx_settlement_batches_result_batch_id');
            });
        }

        if (Schema::hasTable('ticket_items') && $this->hasIndex('ticket_items', 'idx_ticket_items_order_id')) {
            Schema::table('ticket_items', function (Blueprint $table): void {
                $table->dropIndex('idx_ticket_items_order_id');
            });
        }
    }

    private function hasIndex(string $table, string $indexName): bool
    {
        // 使用 Laravel 内置方法，兼容 PostgreSQL 和 SQLite 测试环境
        return Schema::hasIndex($table, $indexName);
    }
};
