<?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('webhooks', function (Blueprint $table) {
            $table->id();
            $table->foreignId('payment_id')->nullable()->constrained('payments')->nullOnDelete();

            $table->string('provider')->default('pagarme');
            $table->string('hook_id')->nullable();
            $table->string('event')->nullable();
            $table->string('account_id')->nullable();
            $table->string('order_id')->nullable();
            $table->string('charge_id')->nullable();
            $table->string('transaction_id')->nullable();
            $table->string('status')->default('received');
            $table->unsignedInteger('attempts_count')->default(1);
            $table->json('payload');
            $table->timestamp('received_at')->nullable();
            $table->timestamp('processed_at')->nullable();
            $table->text('error_message')->nullable();

            $table->timestamps();

            $table->unique(['provider', 'hook_id']);
            $table->index('payment_id');
            $table->index('provider');
            $table->index('event');
            $table->index('account_id');
            $table->index('order_id');
            $table->index('charge_id');
            $table->index('transaction_id');
            $table->index('status');
            $table->index('received_at');
            $table->index('processed_at');
        });
    }

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