<?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('integration_webhooks', function (Blueprint $table) {
            $table->id();
            $table->foreignId('tenant_id')->constrained('tenants')->cascadeOnDelete();
            $table->string('name', 120);
            $table->string('url', 500);
            $table->text('secret_enc');
            $table->json('topics');
            $table->boolean('is_active')->default(true);
            $table->timestamps();

            $table->index(['tenant_id', 'is_active'], 'iwh_tenant_active');
        });

        Schema::create('integration_events', function (Blueprint $table) {
            $table->uuid('id')->primary();
            $table->foreignId('tenant_id')->constrained('tenants')->cascadeOnDelete();
            $table->string('name', 191);
            $table->unsignedInteger('version');
            $table->json('payload');
            $table->string('payload_hash', 64);
            $table->timestamp('occurred_at');
            $table->timestamp('dispatched_at')->nullable();
            $table->timestamp('created_at')->useCurrent();

            $table->index(['tenant_id', 'name', 'version'], 'iev_tenant_name_ver');
            $table->index(['tenant_id', 'dispatched_at'], 'iev_tenant_dispatched');
            $table->unique(['tenant_id', 'payload_hash'], 'iev_tenant_payloadhash_uq');
        });

        Schema::create('integration_webhook_deliveries', function (Blueprint $table) {
            $table->id();
            $table->foreignId('tenant_id')->constrained('tenants')->cascadeOnDelete();
            $table->foreignId('webhook_id')->constrained('integration_webhooks')->cascadeOnDelete();
            $table->uuid('event_id');
            $table->unsignedSmallInteger('attempt')->default(1);
            $table->string('status', 24);
            $table->unsignedSmallInteger('response_status')->nullable();
            $table->text('response_body')->nullable();
            $table->text('error')->nullable();
            $table->timestamp('next_retry_at')->nullable();
            $table->timestamp('delivered_at')->nullable();
            $table->uuid('request_id')->nullable();
            $table->timestamps();

            $table->index(['tenant_id', 'webhook_id', 'created_at'], 'iwhd_t_wh_created');
            $table->index(['tenant_id', 'status', 'next_retry_at'], 'iwhd_t_stat_retry');
            $table->index('event_id', 'iwhd_event_id');
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('integration_webhook_deliveries');
        Schema::dropIfExists('integration_events');
        Schema::dropIfExists('integration_webhooks');
    }
};

