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

            // Identificación
            $table->string('request_uuid', 36)->index();

            // Request técnico
            $table->string('method', 8);
            $table->string('path');
            $table->string('ip', 45)->nullable()->index();
            $table->text('user_agent')->nullable();
            $table->json('headers')->nullable();
            $table->json('query')->nullable();

            // Autenticación / Identidad
            $table->string('auth_type');
            $table->string('bearer_token_hash', 64)->nullable()->index();
            $table->foreignId('license_token_id')->nullable()->constrained('license_tokens')->nullOnDelete();
            $table->foreignId('environment_id')->nullable()->constrained('environments')->nullOnDelete();
            $table->foreignId('client_id')->nullable()->constrained('clients')->nullOnDelete();

            // Datos de negocio (body)
            $table->string('action')->nullable()->index();
            $table->string('plugin')->nullable()->index();
            $table->string('host')->nullable()->index();
            $table->string('version')->nullable();
            $table->string('projectid')->nullable()->index();
            $table->json('environment')->nullable();
            $table->json('payload')->nullable();

            // Resultado
            $table->unsignedSmallInteger('http_status')->index();
            $table->boolean('success')->nullable();
            $table->integer('error_code')->nullable()->index();
            $table->text('error')->nullable();
            $table->unsignedInteger('response_size')->nullable();

            // Rendimiento
            $table->unsignedInteger('duration_ms')->index();
            $table->dateTime('started_at');
            $table->dateTime('ended_at');
        });

        Schema::table('api_request_logs', function (Blueprint $table) {
            $table->index('started_at');
        });
    }

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