<?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('expenses', function (Blueprint $table) {
            $table->id();

            // Multi-tenant isolation
            $table->foreignId('company_id')->constrained()->cascadeOnDelete();

            // Relationship with credit
            $table->foreignId('credit_id')->nullable()->constrained('credits')->nullOnDelete();

            // Relationship with financial operation (if applicable)
            // FK constraint added in enhance_expenses_table_for_accounting migration
            // (financial_operations table is created AFTER this migration)
            $table->unsignedBigInteger('financial_operation_id')->nullable();

            // Who created the record
            $table->foreignId('user_id')->constrained()->cascadeOnDelete();

            // Who executed or registered the expense
            $table->foreignId('collector_user_id')->nullable()->constrained('users')->nullOnDelete();

            // Financial fields
            $table->decimal('amount', 12, 2);
            // Category of the expense
            $table->string('category');
            // Tipo contable del egreso
            $table->string('expense_type')->default('operational');
            // Impacta caja real o no
            $table->boolean('affects_cash')->default(true);
            $table->string('method')->nullable();
            $table->date('operation_date')->nullable();
            $table->string('reference')->nullable();
            $table->text('notes')->nullable();
            $table->json('metadata')->nullable();

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

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