<?php

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

/**
 * Captures "mistakes" — failed requests and exceptions — as the second data
 * axis (alongside enhanced_activity_logs) behind the TPS insights heat-map and
 * per-tenant trial scorecard.
 */
return new class extends Migration
{
    public function up(): void
    {
        if (! Schema::hasTable('activity_incidents')) {
            Schema::create('activity_incidents', function (Blueprint $table) {
                $table->bigIncrements('id');
                $table->unsignedBigInteger('user_id')->nullable()->index();
                $table->unsignedInteger('business_id')->nullable()->index();
                $table->string('type', 20);            // http_error | validation | denied | exception
                $table->unsignedSmallInteger('status_code')->nullable();
                $table->string('route', 255)->nullable();
                $table->string('method', 10)->nullable();
                $table->text('message')->nullable();
                $table->string('exception_class', 191)->nullable();
                $table->string('file', 255)->nullable();
                $table->unsignedInteger('line')->nullable();
                $table->string('url', 500)->nullable();
                $table->string('ip', 45)->nullable();
                $table->string('user_agent', 500)->nullable();
                $table->char('request_id', 36)->nullable()->index();
                $table->timestamp('created_at')->nullable()->index();

                $table->index(['business_id', 'type']);
                $table->index(['business_id', 'created_at']);
            });
        }
    }

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