<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\DB;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        // SQLite doesn't support modifying enums directly/easily.
        // We will create a new table, copy data, drop old, and rename.

        Schema::create('transactions_temp', 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');
            $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);
            $table->string('currency', 3)->default('INR');
            $table->string('payment_gateway')->default('razorpay');
            $table->string('payment_id')->nullable();
            $table->string('order_id')->nullable();
            // Added 'pending_approval' to the enum
            $table->enum('status', ['pending', 'pending_approval', 'processing', 'success', 'failed', 'cancelled', 'refunded'])->default('pending')->index();
            $table->string('payment_method')->nullable();
            $table->json('metadata')->nullable();
            $table->text('failure_reason')->nullable();
            $table->timestamp('payment_started_at')->nullable();
            $table->timestamp('payment_completed_at')->nullable();
            $table->timestamps();
            
            $table->index(['transaction_type', 'reference_id']);
            $table->index('created_at');
        });

        // Copy data
        $oldData = DB::table('transactions')->get();
        foreach ($oldData as $row) {
            DB::table('transactions_temp')->insert((array) $row);
        }

        // Drop old table
        Schema::drop('transactions');

        // Rename new table
        Schema::rename('transactions_temp', 'transactions');
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        // Revert logic (omitted for brevity as this is a fix)
    }
};
