<?php

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

/**
 * Contracts become per-solicitor: each firm has its own set, with the Fintrixor
 * template id stored directly on the contract row. Supersedes (and drops) the
 * solicitor_contract_templates pivot.
 *
 * solicitor_id is added without a DB foreign key (SQLite, used by the test
 * suite, can't add a FK to an existing table); BelongsToSolicitor stamps it.
 */
return new class extends Migration {
    public function up(): void
    {
        Schema::table('contracts', function (Blueprint $t) {
            if (! Schema::hasColumn('contracts', 'solicitor_id')) {
                $t->unsignedBigInteger('solicitor_id')->nullable();
                $t->index('solicitor_id');
            }
            if (! Schema::hasColumn('contracts', 'fintrixor_template_id')) {
                $t->string('fintrixor_template_id')->nullable();
            }
        });

        Schema::dropIfExists('solicitor_contract_templates');
    }

    public function down(): void
    {
        Schema::table('contracts', function (Blueprint $t) {
            $t->dropIndex(['solicitor_id']);
            $t->dropColumn(['solicitor_id', 'fintrixor_template_id']);
        });
    }
};
