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

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

            $table->foreignId('assigned_agent_id')->nullable()->constrained('users')->nullOnDelete();
            $table->foreignId('answered_by_agent_id')->nullable()->constrained('users')->nullOnDelete();
            $table->foreignId('solicitor_phone_number_id')->nullable()->constrained()->nullOnDelete();

            $table->string('provider', 50)->default('twilio');
            $table->string('provider_call_sid')->nullable()->unique();

            $table->string('from_number', 50)->nullable()->index();
            $table->string('to_number', 50)->nullable()->index();

            $table->string('phone_number_type_slug', 50)->nullable()->index();
            $table->string('call_type', 50)->nullable()->index();
            $table->string('queue_type', 50)->nullable()->index();

            $table->string('target_label')->nullable();
            $table->string('target_type', 100)->nullable()->index();

            $table->boolean('is_recorded')->default(true);
            $table->boolean('recording_notice_played')->default(false);

            $table->timestamp('queued_at')->nullable();
            $table->timestamp('connected_at')->nullable();
            $table->timestamp('wrap_up_until')->nullable();

            $table->unsignedInteger('queue_wait_seconds')->nullable();
            $table->unsignedInteger('ring_seconds')->nullable();

            $table->text('notes')->nullable();
            $table->json('meta')->nullable();

            $table->timestamps();

            $table->index(['solicitor_id', 'assigned_agent_id']);
            $table->index(['solicitor_id', 'answered_by_agent_id']);
            $table->index(['solicitor_id', 'queue_type']);
            $table->index(['solicitor_id', 'call_type']);
            $table->index(['solicitor_id', 'solicitor_phone_number_id']);
        });
    }

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