<?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::table('integration_webhooks', function (Blueprint $table) {
            $table->string('health_status', 24)->default('healthy')->after('is_active');
            $table->timestamp('last_success_at')->nullable()->after('health_status');
            $table->timestamp('last_failure_at')->nullable()->after('last_success_at');
            $table->unsignedInteger('failure_count')->default(0)->after('last_failure_at');

            $table->index(['tenant_id', 'health_status'], 'iwh_tenant_health');
        });

        Schema::table('integration_webhook_deliveries', function (Blueprint $table) {
            $table->unsignedSmallInteger('attempt_count')->default(0)->after('attempt');
            $table->timestamp('first_attempted_at')->nullable()->after('attempt_count');
            $table->timestamp('last_attempted_at')->nullable()->after('first_attempted_at');
            $table->timestamp('dead_lettered_at')->nullable()->after('last_attempted_at');
            $table->timestamp('exhausted_at')->nullable()->after('dead_lettered_at');
            $table->unsignedInteger('duration_ms')->nullable()->after('exhausted_at');

            $table->index(['tenant_id', 'status', 'dead_lettered_at'], 'iwhd_t_stat_dead');
        });
    }

    public function down(): void
    {
        Schema::table('integration_webhook_deliveries', function (Blueprint $table) {
            $table->dropIndex('iwhd_t_stat_dead');
            $table->dropColumn([
                'attempt_count',
                'first_attempted_at',
                'last_attempted_at',
                'dead_lettered_at',
                'exhausted_at',
                'duration_ms',
            ]);
        });

        Schema::table('integration_webhooks', function (Blueprint $table) {
            $table->dropIndex('iwh_tenant_health');
            $table->dropColumn([
                'health_status',
                'last_success_at',
                'last_failure_at',
                'failure_count',
            ]);
        });
    }
};
