<?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('payment_transactions', function (Blueprint $table): void {
            $table->ulid('id')->primary();
            $table->foreignUlid('user_id')->nullable()->constrained('users')->nullOnDelete();
            $table->foreignUlid('credit_product_id')->nullable()->constrained('credit_products')->nullOnDelete();
            $table->foreignUlid('credit_ledger_entry_id')->nullable()->constrained('credit_ledger_entries')->nullOnDelete();
            $table->string('type', 64);
            $table->string('status', 64);
            $table->string('stripe_event_id')->nullable()->index();
            $table->string('stripe_event_type')->nullable()->index();
            $table->string('stripe_customer_id')->nullable()->index();
            $table->string('stripe_checkout_session_id')->nullable()->index();
            $table->string('stripe_invoice_id')->nullable()->index();
            $table->string('stripe_payment_intent_id')->nullable()->index();
            $table->string('stripe_subscription_id')->nullable()->index();
            $table->string('stripe_price_id')->nullable()->index();
            $table->unsignedInteger('amount')->nullable();
            $table->string('currency', 3)->nullable();
            $table->unsignedInteger('credits_expected')->nullable();
            $table->unsignedInteger('credits_granted')->default(0);
            $table->text('error_message')->nullable();
            $table->json('payload')->nullable();
            $table->timestamp('processed_at')->nullable();
            $table->timestamps();

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

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