<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::table('transactions', function (Blueprint $table) {
            // Drop enum constraint by changing to string if possible, or just raw SQL for ENUM change if needed.
            // Since this is MySQL, we can just use string()->change() in Laravel 10+
            $table->string('type', 50)->change();
        });
        
        // MariaDB < 10.5.2 doesn't support RENAME COLUMN natively without DBAL. 
        DB::statement('ALTER TABLE transactions CHANGE amount_lkr payment_amount DECIMAL(18,4) NOT NULL DEFAULT 0');

        Schema::table('transactions', function (Blueprint $table) {
            
            $table->foreignId('payment_currency_id')->nullable()->constrained('currencies')->nullOnDelete()->after('payment_amount');
            $table->foreignId('payment_account_id')->nullable()->constrained('accounts')->nullOnDelete()->after('payment_currency_id');
            $table->foreignId('agent_id')->nullable()->constrained()->nullOnDelete()->after('id');
            
            $table->timestamp('borrow_settled_at')->nullable();
            $table->foreignId('borrow_settlement_id')->nullable()->constrained('transactions')->nullOnDelete();

            $table->dropColumn('net_quantity');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('transactions', function (Blueprint $table) {
            $table->decimal('net_quantity', 18, 4)->default(0)->after('quantity');
            $table->dropForeign(['borrow_settlement_id']);
            $table->dropColumn('borrow_settlement_id');
            $table->dropColumn('borrow_settled_at');
            $table->dropForeign(['agent_id']);
            $table->dropColumn('agent_id');
            $table->dropForeign(['payment_currency_id']);
            $table->dropColumn('payment_currency_id');
            $table->renameColumn('payment_amount', 'amount_lkr');
        });
    }
};
