<?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()->onDelete('cascade');
            $table->foreignId('seller_id')->nullable()->constrained()->onDelete('set null');
            $table->enum('transaction_type', ['subscription', 'promotion'])->index();
            $table->unsignedBigInteger('reference_id'); // subscription_id or product_promotion_id
            $table->decimal('amount', 10, 2);
            $table->decimal('platform_commission', 10, 2)->default(0);
            $table->decimal('gst_amount', 10, 2)->default(0);
            $table->decimal('total_amount', 10, 2); // amount + commission + gst
            $table->string('currency', 3)->default('INR');
            $table->string('payment_gateway')->default('razorpay'); // razorpay, paypal
            $table->string('payment_id')->nullable();
            $table->string('order_id')->nullable();
            $table->enum('status', ['pending', 'processing', 'success', 'failed', 'cancelled', 'refunded'])->default('pending')->index();
            $table->string('payment_method')->nullable(); // card, upi, netbanking, wallet, paypal
            $table->json('metadata')->nullable(); // Store package details, product details, etc.
            $table->text('failure_reason')->nullable();
            $table->timestamp('payment_started_at')->nullable();
            $table->timestamp('payment_completed_at')->nullable();
            $table->timestamps();
            
            // Indexes
            $table->index(['transaction_type', 'reference_id']);
            $table->index('created_at');
        });
    }

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