<?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('calls', function (Blueprint $table) {
            $table->string('disposition', 100)->nullable()->after('notes');
            $table->timestamp('callback_at')->nullable()->after('disposition');
            $table->index(['solicitor_id', 'disposition']);
        });

        // Backfill from meta JSON for any existing wrap-up records.
        // NULLIF guards against JSON_UNQUOTE returning the literal string 'null'
        // when the JSON value is null, which MySQL rejects as an invalid datetime.
        DB::statement("
            UPDATE calls
            SET
                disposition = NULLIF(JSON_UNQUOTE(JSON_EXTRACT(meta, '$.wrap_up.disposition')), 'null'),
                callback_at = NULLIF(NULLIF(JSON_UNQUOTE(JSON_EXTRACT(meta, '$.wrap_up.callback_at')), 'null'), '')
            WHERE JSON_EXTRACT(meta, '$.wrap_up') IS NOT NULL
        ");
    }

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