<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * Time-series history of agent presence. Each row is a single interval the
     * agent spent in one status (started_at → ended_at). The currently-open
     * interval has a null ended_at. Mirrors the claim `status_histories` table.
     */
    public function up(): void
    {
        Schema::create('agent_status_histories', function (Blueprint $table) {
            $table->id();
            $table->foreignId('solicitor_id')->constrained()->cascadeOnDelete();
            $table->foreignId('agent_id')->constrained('users')->cascadeOnDelete();

            $table->string('status', 50)->index();

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

            $table->foreignId('communication_id')->nullable()->constrained()->nullOnDelete();
            $table->string('source', 50)->nullable();

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

            $table->timestamps();

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

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('agent_status_histories');
    }
};
