<?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('care_financial_obligations')) {
            return;
        }

        $hasUnique = collect(Schema::getIndexes('care_financial_obligations'))
            ->contains(fn (array $index) => ($index['name'] ?? '') === 'care_obligations_visit_stage_unique');

        if ($hasUnique) {
            return;
        }

        Schema::table('care_financial_obligations', function (Blueprint $table) {
            $table->unique(
                ['visit_id', 'workflow_stage_id'],
                'care_obligations_visit_stage_unique',
            );
        });
    }

    public function down(): void
    {
        if (! Schema::hasTable('care_financial_obligations')) {
            return;
        }

        $hasUnique = collect(Schema::getIndexes('care_financial_obligations'))
            ->contains(fn (array $index) => ($index['name'] ?? '') === 'care_obligations_visit_stage_unique');

        if (! $hasUnique) {
            return;
        }

        Schema::table('care_financial_obligations', function (Blueprint $table) {
            $table->dropUnique('care_obligations_visit_stage_unique');
        });
    }
};
