<?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
    {
        Schema::table('accounts', function (Blueprint $table) {
            // Drop existing unique index if present (contract_id, reference, deleted_at)
            try {
                $table->dropUnique('accounts_reference_unique');
            } catch (\Throwable $e) {
                // ignore if it does not exist
            }
            // Recreate including active flag so archived/inactive accounts can reuse reference
            $table->unique(['contract_id', 'reference', 'active', 'deleted_at'], 'accounts_reference_unique');
        });
    }

    public function down(): void
    {
        Schema::table('accounts', function (Blueprint $table) {
            try {
                $table->dropUnique('accounts_reference_unique');
            } catch (\Throwable $e) {
                // ignore
            }
            // Restore previous definition without active
            $table->unique(['contract_id', 'reference', 'deleted_at'], 'accounts_reference_unique');
        });
    }
};
