<?php

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

return new class extends Migration
{
    public function up(): void
    {
        $driver = DB::getDriverName();
        if ($driver === 'pgsql') {
            // Drop constraint if exists (covers both constraint-created and index-created uniqueness)
            try {
                DB::statement('ALTER TABLE payments DROP CONSTRAINT IF EXISTS payments_account_id_reference_unique');
            } catch (\Throwable $e) {
                // ignore
            }
            // Drop index if exists
            try {
                DB::statement('DROP INDEX IF EXISTS payments_account_id_reference_unique');
            } catch (\Throwable $e) {
                // ignore
            }

            // Create a partial unique index that ignores soft-deleted rows, use a new name
            DB::statement('CREATE UNIQUE INDEX IF NOT EXISTS uniq_payments_account_reference_not_deleted ON payments (account_id, reference) WHERE deleted_at IS NULL');
        } else {
            // Fallback for other drivers: ensure a regular unique index exists (no partial support)
            Schema::table('payments', function ($table): void {
                try {
                    $table->unique(['account_id', 'reference'], 'payments_account_id_reference_unique');
                } catch (\Throwable $e) {
                    // ignore if already exists
                }
            });
        }
    }

    public function down(): void
    {
        $driver = DB::getDriverName();
        if ($driver === 'pgsql') {
            DB::statement('DROP INDEX IF EXISTS uniq_payments_account_reference_not_deleted');
            // Recreate a standard unique index (non-partial) with the original name
            DB::statement('CREATE UNIQUE INDEX IF NOT EXISTS payments_account_id_reference_unique ON payments (account_id, reference)');
        } else {
            // For other drivers, nothing special beyond ensuring the standard index exists
            Schema::table('payments', function ($table): void {
                try {
                    $table->unique(['account_id', 'reference'], 'payments_account_id_reference_unique');
                } catch (\Throwable $e) {
                    // ignore
                }
            });
        }
    }
};
