<?php

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

/**
 * Additive upgrade of contract_requests. The request is now the grouping for a
 * fan-out of esign_documents; its `status` is an aggregate (cast to EsignStatus)
 * and per-document timestamps live on esign_documents. Existing rows preserved.
 */
return new class extends Migration {
    public function up(): void
    {
        // solicitor_id added WITHOUT a DB foreign key: SQLite (test suite) cannot
        // add a FK to an existing table via ALTER. Stamped explicitly by the app.
        Schema::table('contract_requests', function (Blueprint $table) {
            if (! Schema::hasColumn('contract_requests', 'solicitor_id')) {
                $table->unsignedBigInteger('solicitor_id')->nullable();
                $table->index('solicitor_id');
            }
            $table->index('status');
        });

        // Backfill (portable correlated subquery; no-op on an empty table).
        DB::table('contract_requests')->whereNull('solicitor_id')->update([
            'solicitor_id' => DB::raw('(select solicitor_id from clients where clients.id = contract_requests.client_id)'),
        ]);

        // Legacy status 'pending' → 'draft' ('sent' is already a valid EsignStatus).
        DB::table('contract_requests')->where('status', 'pending')->update(['status' => 'draft']);
    }

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