<?php

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::table('synapse_transcripts', function (Blueprint $table) {
            $table->unsignedBigInteger('solicitor_id')->nullable()->after('recording_id');
        });

        // Backfill from the related recording's solicitor_id.
        DB::statement('
            UPDATE synapse_transcripts st
            INNER JOIN recordings r ON r.id = st.recording_id
            SET st.solicitor_id = r.solicitor_id
        ');

        Schema::table('synapse_transcripts', function (Blueprint $table) {
            $table->unsignedBigInteger('solicitor_id')->nullable(false)->change();
            $table->foreign('solicitor_id')->references('id')->on('solicitors')->cascadeOnDelete();
            $table->index('solicitor_id');
        });
    }

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