<?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('account_credit_deposits')) {
            return;
        }

        Schema::create('account_credit_deposits', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained()->cascadeOnDelete();
            $table->unsignedBigInteger('whmcs_client_id')->index();

            // amount/currency are always the WHMCS client-account credit amount.
            $table->decimal('amount', 14, 2);
            $table->string('currency', 3);

            // PayFast currently settles in PKR. Preserve the exact conversion
            // snapshot so later WHMCS rate changes cannot alter this deposit.
            $table->decimal('payable_amount', 14, 2);
            $table->string('payable_currency', 3);
            $table->decimal('conversion_rate', 18, 8)->nullable();
            $table->json('currency_snapshot')->nullable();

            $table->string('basket_id', 100)->unique();
            $table->string('transaction_id', 150)->nullable()->unique();
            $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->decimal('callback_amount', 14, 2)->nullable();
            $table->decimal('merchant_amount', 14, 2)->nullable();
            $table->string('callback_currency', 3)->nullable();
            $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->decimal('whmcs_balance_after', 14, 2)->nullable();
            $table->timestamps();

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

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