<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('ledger_entries', function (Blueprint $table) {
            $table->id();
            $table->date('ledger_date');
            $table->enum('entry_type', ['expense', 'refund', 'advance', 'adjustment']);
            $table->enum('reference_type', ['order', 'manual'])->default('manual');
            $table->unsignedBigInteger('reference_id')->nullable();
            $table->string('payment_mode', 50);
            $table->decimal('amount', 14, 2);
            $table->text('remarks')->nullable();
            $table->foreignId('created_by')->constrained('users')->cascadeOnDelete();
            $table->timestamps();

            $table->index('ledger_date');
            $table->index('payment_mode');
            $table->index('entry_type');
            $table->index(['reference_type', 'reference_id']);
        });

        // Enforce non-negative amounts at DB level where supported.
        if (Schema::getConnection()->getDriverName() !== 'sqlite') {
            DB::statement('ALTER TABLE ledger_entries ADD CONSTRAINT chk_ledger_entries_amount_non_negative CHECK (amount >= 0)');
        }
    }

    public function down(): void
    {
        Schema::dropIfExists('ledger_entries');
    }
};
