<?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('transactions', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained()->cascadeOnDelete();
            $table->foreignId('category_id')->constrained('categories')->cascadeOnDelete();
            $table->foreignId('plan_id')->nullable()->constrained()->nullOnDelete();
            $table->foreignId('vendor_id')->nullable()->constrained()->nullOnDelete();
            $table->string('internal_reference', 191)->unique();
            $table->string('vendor_reference', 191)->nullable();
            $table->decimal('amount_charged', 14, 2);
            $table->decimal('vendor_cost', 14, 2)->nullable();
            $table->decimal('profit', 14, 2)->nullable();
            $table->enum('status', ['pending', 'success', 'failed', 'reversed', 'stuck'])->default('pending');
            $table->unsignedInteger('attempt_count')->default(0);
            $table->string('last_error')->nullable();
            $table->json('meta_json')->nullable();
            $table->timestamp('webhook_received_at')->nullable();
            $table->timestamps();

            $table->index(['status', 'created_at']);
            $table->index(['vendor_id', 'status']);
            $table->index(['category_id', 'status']);
            $table->index('vendor_reference');
        });

        Schema::create('vendor_transaction_logs', function (Blueprint $table) {
            $table->id();
            $table->foreignId('transaction_id')->constrained('transactions')->cascadeOnDelete();
            $table->foreignId('vendor_id')->nullable()->constrained('vendors')->nullOnDelete();
            $table->string('endpoint');
            $table->json('request_json')->nullable();
            $table->json('response_json')->nullable();
            $table->unsignedSmallInteger('http_code')->nullable();
            $table->unsignedInteger('duration_ms')->nullable();
            $table->timestamp('created_at')->useCurrent();

            $table->index(['transaction_id', 'vendor_id']);
        });
    }

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

