<?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::create('call_scores', function (Blueprint $table) {
            $table->id();
            $table->foreignId('solicitor_id')->constrained()->cascadeOnDelete();
            $table->foreignId('recording_id')->unique()->constrained()->cascadeOnDelete();
            $table->foreignId('communication_id')->nullable()->constrained()->nullOnDelete();
            $table->foreignId('call_id')->nullable()->constrained()->nullOnDelete();

            $table->boolean('is_initial_call')->nullable();
            $table->string('status')->default('processing'); // processing | completed | failed

            // Score fields — null when not an initial call or still processing
            $table->unsignedTinyInteger('total_score')->nullable();
            $table->string('risk_rating')->nullable(); // low_risk | acceptable | compliance_concern | high_risk
            $table->boolean('passed')->nullable();
            $table->boolean('auto_fail')->default(false);
            $table->json('auto_fail_triggers')->nullable();
            $table->json('section_scores')->nullable();
            $table->text('summary')->nullable();
            $table->longText('raw_output')->nullable();

            $table->text('error')->nullable();
            $table->timestamps();

            $table->index(['solicitor_id', 'status']);
            $table->index(['solicitor_id', 'risk_rating']);
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('call_scores');
    }
};
