<?php

use Hyperf\Database\Schema\Schema;
use Hyperf\Database\Schema\Blueprint;
use Hyperf\Database\Migrations\Migration;

return new class extends Migration {

    public function up(): void
    {
        /**
         * CHART OF ACCOUNTS (Self-Referencing)
         */
        Schema::create('accounts', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('hashkey', 300)->unique();
            
            // Self-referencing foreign key for nested accounts
            $table->unsignedBigInteger('parent_id')->nullable();
            $table->foreign('parent_id')->references('id')->on('accounts')->cascadeOnDelete();

            $table->string('name')->index();
            $table->string('type')->index(); // e.g., 'REVENUE', 'EXPENSE'
            $table->string('description')->nullable();
            $table->boolean('is_active')->default(true);

            $table->unsignedBigInteger('created_by')->nullable();
            $table->unsignedBigInteger('updated_by')->nullable();

            $table->foreign('created_by')->references('id')->on('users')->nullOnDelete();
            $table->foreign('updated_by')->references('id')->on('users')->nullOnDelete();

            $table->timestamps();
        });

        /**
         * ACCOUNT TRANSACTIONS
         */
        Schema::create('account_transactions', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('hashkey', 300)->unique();

            // Link to the lowest-level account
            $table->unsignedBigInteger('account_id');
            $table->foreign('account_id')->references('id')->on('accounts')->cascadeOnDelete();

            $table->string('item')->index()->nullable();

            $table->unsignedBigInteger('target_id')->nullable()->index(); // optional target (user, vendor)

            $table->decimal('amount', 15, 2)->default(0);
            $table->dateTime('transaction_date')->index();
            $table->string('reference')->nullable()->index(); // external reference / invoice no.

            $table->json('additional_details')->nullable();

            $table->unsignedBigInteger('created_by')->nullable();
            $table->unsignedBigInteger('updated_by')->nullable();

            $table->foreign('created_by')->references('id')->on('users')->nullOnDelete();
            $table->foreign('updated_by')->references('id')->on('users')->nullOnDelete();

            $table->timestamps();
        });
    }

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