<?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
    {
        if (Schema::hasTable('payfast_payments')) {
            return;
        }

        Schema::create('payfast_payments', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->nullable()->constrained()->nullOnDelete();
            $table->foreignId('invoice_id')->constrained()->cascadeOnDelete();
            $table->unsignedBigInteger('whmcs_invoice_id')->index();
            $table->string('basket_id', 100)->unique();
            $table->string('transaction_id', 150)->nullable()->unique();
            $table->decimal('expected_amount', 14, 2);
            $table->string('expected_currency', 3);
            $table->decimal('callback_amount', 14, 2)->nullable();
            $table->decimal('merchant_amount', 14, 2)->nullable();
            $table->string('callback_currency', 3)->nullable();
            $table->timestamp('order_date');
            $table->string('signature', 128);
            $table->string('mode', 20)->default('sandbox');
            $table->string('gateway', 80)->default('payfast');
            $table->string('status', 50)->default('initiated')->index();
            $table->string('payfast_error_code', 30)->nullable()->index();
            $table->text('payfast_error_message')->nullable();
            $table->string('validation_hash', 128)->nullable();
            $table->json('callback_payload')->nullable();
            $table->timestamp('callback_received_at')->nullable()->index();
            $table->timestamp('verified_at')->nullable();
            $table->timestamp('whmcs_synced_at')->nullable();
            $table->unsignedInteger('sync_attempts')->default(0);
            $table->timestamp('next_retry_at')->nullable()->index();
            $table->text('last_error')->nullable();
            $table->timestamps();

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

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