<?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(); // BIGINT UNSIGNED AI PK

            // Polymorphic relation (explicit to match lengths/types)
            $table->string('transactionable_type', 191);
            $table->unsignedBigInteger('transactionable_id');
            $table->index(
                ['transactionable_type', 'transactionable_id'],
                'transactions_transactionable_type_transactionable_id_index'
            );

            $table->timestamp('created_at')->nullable();
            $table->timestamp('updated_at')->nullable();

            $table->string('invoice_no', 191)->nullable();
            $table->string('date', 191); // stored as VARCHAR per schema
            $table->string('redirect_path', 191)->nullable();
            $table->string('balance_type', 191)->nullable();

            // FKs / owners
            $table->foreignId('account_id')
                  ->constrained('accounts')
                  ->cascadeOnUpdate()
                  ->restrictOnDelete();

            $table->decimal('amount', 16, 2)->nullable()->default(0.00);

            $table->foreignId('created_by')
                  ->constrained('users')
                  ->cascadeOnUpdate()
                  ->restrictOnDelete();

            $table->foreignId('company_id')
                  ->constrained('companies')
                  ->cascadeOnUpdate()
                  ->restrictOnDelete();

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

            $table->string('description', 191)->nullable();
            $table->string('transaction_item_type', 191)->nullable();
            $table->string('batch_id', 191)->nullable();

            $table->decimal('debit_amount', 16, 4)->nullable()->default(0.0000);
            $table->decimal('credit_amount', 16, 4)->nullable()->default(0.0000);
        });
    }

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

