<?php

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::table('settlement_adjustments', function (Blueprint $table): void {
            $table->foreignId('result_bill_id')
                ->nullable()
                ->after('original_bill_id')
                ->constrained('settlement_bills')
                ->nullOnDelete();
        });

        Schema::table('payment_records', function (Blueprint $table): void {
            $table->dropIndex(['settlement_bill_id', 'idempotency_key']);
        });

        Schema::table('settlement_adjustments', function (Blueprint $table): void {
            $table->dropIndex(['original_bill_id', 'idempotency_key']);
        });

        DB::statement(
            'CREATE UNIQUE INDEX payment_records_bill_idempotency_unique '
            .'ON payment_records (settlement_bill_id, idempotency_key) '
            ."WHERE idempotency_key IS NOT NULL AND idempotency_key <> ''",
        );

        DB::statement(
            'CREATE UNIQUE INDEX settlement_adjustments_bill_idempotency_unique '
            .'ON settlement_adjustments (original_bill_id, idempotency_key) '
            ."WHERE idempotency_key IS NOT NULL AND idempotency_key <> ''",
        );
    }

    public function down(): void
    {
        DB::statement('DROP INDEX IF EXISTS payment_records_bill_idempotency_unique');
        DB::statement('DROP INDEX IF EXISTS settlement_adjustments_bill_idempotency_unique');

        Schema::table('payment_records', function (Blueprint $table): void {
            $table->index(['settlement_bill_id', 'idempotency_key']);
        });

        Schema::table('settlement_adjustments', function (Blueprint $table): void {
            $table->index(['original_bill_id', 'idempotency_key']);
            $table->dropConstrainedForeignId('result_bill_id');
        });
    }
};