<?php
// database/migrations/xxxx_create_omniboard_schema.php

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

return new class extends Migration
{
    public function up()
    {
        // 1. Tenants (Clientes SaaS)
        Schema::create('tenants', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('api_key')->unique(); // Token para o Agente Local
            $table->timestamps();
        });

        // 2. Queues (Filas de Voz ou Chat)
        Schema::create('queues', function (Blueprint $table) {
            $table->id();
            $table->foreignId('tenant_id')->constrained()->cascadeOnDelete();
            $table->string('name')->nullable();
            $table->string('type')->default('voice'); // voice, whatsapp
            $table->string('source_id')->nullable(); // ID no Asterisk/Helena
            $table->integer('sla_threshold')->default(20); // Meta de SLA em segundos
            $table->timestamps();
        });

        // 3. Agents (Atendentes)
        Schema::create('agents', function (Blueprint $table) {
            $table->id();
            $table->foreignId('tenant_id')->constrained()->cascadeOnDelete();

            $table->string('name'); // Ex: "Lucas Gomes"

            // MUDANÇA 1: De 'extension' para 'interface'
            // Armazena "PJSIP/200". É a chave que liga o AMI ao Banco.
            $table->string('interface')->index();

            // Status atual
            $table->enum('status', ['available', 'paused', 'talking', 'offline'])
                ->default('offline');

            // MUDANÇA 2: Motivo da pausa (vindo do AMI)
            $table->string('pause_reason')->nullable();

            // Monitoramento de tempo
            $table->timestamp('last_status_change')->useCurrent();

            // MUDANÇA 3: Métricas acumuladas simples (KPIs)
            $table->integer('total_calls_answered')->default(0);
            $table->integer('total_ring_no_answer')->default(0);

            $table->timestamps();
        });

        // 4. Calls (Histórico detalhado)
        Schema::create('calls', function (Blueprint $table) {
            $table->uuid('id')->primary();
            $table->foreignId('tenant_id')->constrained()->cascadeOnDelete();
            $table->foreignId('queue_id')->constrained()->cascadeOnDelete();
            $table->foreignId('agent_id')->nullable()->constrained('agents');
            $table->string('caller_id'); // Telefone ou Nome
            $table->enum('status', ['waiting', 'answered', 'abandoned']);
            $table->integer('wait_time')->default(0); // Segundos na fila
            $table->integer('talk_time')->default(0); // Segundos falando
            $table->timestamp('entered_at');
            $table->timestamp('finished_at')->nullable();
            $table->timestamps();
        });

        // 5. Daily Metrics (Snapshot consolidado para o Dashboard carregar rápido)
        Schema::create('daily_metrics', function (Blueprint $table) {
            $table->id();
            $table->foreignId('queue_id')->constrained()->cascadeOnDelete();
            $table->date('date');

            // Métricas visíveis na imagem
            $table->integer('received_count')->default(0);
            $table->integer('answered_count')->default(0);
            $table->integer('abandoned_count')->default(0);
            $table->decimal('sla_percentage', 5, 2)->default(0); // Ex: 96.50
            $table->integer('avg_wait_time')->default(0); // Em segundos
            $table->integer('avg_talk_time')->default(0); // Em segundos
            $table->integer('max_wait_time')->default(0); // Em segundos
            $table->integer('transferred_count')->default(0);

            $table->timestamps();

            // Garante uma métrica por fila por dia
            $table->unique(['queue_id', 'date']);
        });

        // 6. Waiting List (Barra lateral "Próximos Atendimentos")
        Schema::create('waiting_list', function (Blueprint $table) {
            $table->id();
            $table->foreignId('queue_id')->constrained()->cascadeOnDelete();
            $table->string('caller_name')->nullable();
            $table->string('caller_number');
            $table->timestamp('entered_at');
            $table->integer('attempt_count')->default(1);
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('waiting_list');
        Schema::dropIfExists('daily_metrics');
        Schema::dropIfExists('calls');
        Schema::dropIfExists('agents');
        Schema::dropIfExists('queues');
        Schema::dropIfExists('tenants');
    }
};
