<?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->uuid('uuid')->unique();
            $table->foreignId('academy_id')->constrained()->cascadeOnDelete();
            $table->foreignId('debit_account_id')->constrained('financial_accounts');
            $table->foreignId('credit_account_id')->constrained('financial_accounts');
            $table->foreignId('payment_id')->nullable()->constrained()->nullOnDelete();
            $table->foreignId('invoice_id')->nullable()->constrained()->nullOnDelete();

            $table->nullableMorphs('reference');

            $table->bigInteger('amount');
            $table->string('currency', 3)->default('EGP');
            $table->string('type', 30);
            $table->text('description')->nullable();
            $table->date('transaction_date');
            $table->jsonb('metadata')->default('{}');

            $table->foreignId('created_by')->nullable()->constrained('users')->nullOnDelete();

            $table->timestamps();

            $table->index(['academy_id', 'transaction_date']);
            $table->index(['academy_id', 'type']);
            $table->index('debit_account_id');
            $table->index('credit_account_id');
        });

        DB::statement("ALTER TABLE transactions ADD CONSTRAINT transactions_type_check CHECK (type IN ('payment_received', 'payment_made', 'refund', 'transfer', 'adjustment', 'fee', 'discount', 'write_off', 'opening_balance'))");
    }

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