<?php

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

/**
 * Repair indexes skipped when an earlier deploy created care_facility_workflows
 * then failed on the too-long auto-generated composite index name.
 */
return new class extends Migration
{
    public function up(): void
    {
        if (! Schema::hasTable('care_facility_workflows')) {
            return;
        }

        $indexes = collect(Schema::getIndexes('care_facility_workflows'))
            ->mapWithKeys(fn (array $index) => [($index['name'] ?? '') => $index]);

        Schema::table('care_facility_workflows', function (Blueprint $table) use ($indexes) {
            if (! $indexes->has('care_facility_workflows_uuid_unique')) {
                $table->unique('uuid', 'care_facility_workflows_uuid_unique');
            }

            if (! $indexes->has('care_facility_workflows_owner_ref_index')) {
                $table->index('owner_ref', 'care_facility_workflows_owner_ref_index');
            }

            if (! $indexes->has('care_fw_org_branch_active_idx')
                && ! $indexes->has('care_facility_workflows_organization_id_branch_id_is_active_index')) {
                $table->index(
                    ['organization_id', 'branch_id', 'is_active'],
                    'care_fw_org_branch_active_idx',
                );
            }
        });
    }

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

        $indexes = collect(Schema::getIndexes('care_facility_workflows'))
            ->mapWithKeys(fn (array $index) => [($index['name'] ?? '') => $index]);

        Schema::table('care_facility_workflows', function (Blueprint $table) use ($indexes) {
            if ($indexes->has('care_fw_org_branch_active_idx')) {
                $table->dropIndex('care_fw_org_branch_active_idx');
            }
            if ($indexes->has('care_facility_workflows_owner_ref_index')) {
                $table->dropIndex('care_facility_workflows_owner_ref_index');
            }
            if ($indexes->has('care_facility_workflows_uuid_unique')) {
                $table->dropUnique('care_facility_workflows_uuid_unique');
            }
        });
    }
};
