<?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('communications', function (Blueprint $table)
        {
            $table->id();

            $table->foreignId('solicitor_id')->constrained()->cascadeOnDelete();

            $table->foreignId('claim_id')->nullable()->constrained()->nullOnDelete();
            $table->foreignId('agent_id')->nullable()->constrained('users')->nullOnDelete();

            $table->nullableMorphs('communicable');

            $table->string('channel', 50);   // voice, sms, whatsapp, email
            $table->string('direction', 50); // inbound, outbound
            $table->string('status', 50)->index();

            $table->timestamp('started_at')->nullable()->index();
            $table->timestamp('answered_at')->nullable();
            $table->timestamp('ended_at')->nullable();
            $table->unsignedInteger('duration')->nullable();

            $table->string('subject')->nullable();
            $table->text('preview')->nullable();
            $table->json('meta')->nullable();

            $table->timestamps();

            $table->index(['solicitor_id', 'channel']);
            $table->index(['solicitor_id', 'direction']);
            $table->index(['solicitor_id', 'claim_id']);
            $table->index(['solicitor_id', 'agent_id']);
        });
    }

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