<?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('client_cases', function (Blueprint $table) {
            if (! Schema::hasColumn('client_cases', 'client_ref')) {
                $table->string('client_ref', 191)->nullable()->after('person_id');
            }
            // Add indexes
            $table->index('client_ref');
            // Composite unique per client for client_ref
            $table->unique(['client_id', 'client_ref']);
        });
    }

    public function down(): void
    {
        Schema::table('client_cases', function (Blueprint $table) {
            if (Schema::hasColumn('client_cases', 'client_ref')) {
                // Drop constraints first
                try {
                    $table->dropUnique('client_cases_client_id_client_ref_unique');
                } catch (\Throwable $e) {
                }
                try {
                    $table->dropIndex('client_cases_client_ref_index');
                } catch (\Throwable $e) {
                }
                $table->dropColumn('client_ref');
            }
        });
    }
};
