<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

/**
 * Phase 1: Enhance expenses table for proper accounting.
 *
 * Adds columns to track:
 * - Whether expense affects profit (operating expenses)
 * - Whether expense reduces capital (disbursements, write-offs)
 * - Locking mechanism for financial integrity
 * - Approval workflow for sensitive transactions
 *
 * ACCOUNTING RULES:
 * - credit_disbursement: reduces_capital=true, affects_profit=false
 * - salary_wages/rent/etc: reduces_capital=false, affects_profit=true
 * - profit_withdrawal: reduces_capital=false, affects_profit=true (retained earnings)
 * - bad_debt_writeoff: reduces_capital=true, affects_profit=false (already provisioned)
 */
return new class extends Migration
{
    public function up(): void
    {
        Schema::table('expenses', function (Blueprint $table) {
            // Add deferred FK to financial_operations (created after expenses table)
            $table->foreign('financial_operation_id')
                ->references('id')
                ->on('financial_operations')
                ->nullOnDelete();

            // Financial impact flags
            $table->boolean('affects_profit')
                ->default(true)
                ->after('affects_cash')
                ->comment('True if expense reduces profit (operating expenses)');

            $table->boolean('reduces_capital')
                ->default(false)
                ->after('affects_profit')
                ->comment('True if expense reduces working capital (disbursements, write-offs)');

            // Locking mechanism for financial integrity
            $table->boolean('is_locked')
                ->default(false)
                ->after('metadata')
                ->comment('Locked records cannot be edited or deleted');

            $table->timestamp('locked_at')
                ->nullable()
                ->after('is_locked')
                ->comment('When the record was locked');

            $table->string('lock_reason', 255)
                ->nullable()
                ->after('locked_at')
                ->comment('Reason for locking (auto-lock, manual, system)');

            // Approval workflow
            $table->boolean('requires_approval')
                ->default(false)
                ->after('lock_reason')
                ->comment('True if this expense type requires approval');

            $table->string('approval_status', 50)
                ->default('approved')
                ->after('requires_approval')
                ->comment('pending, approved, rejected');

            $table->foreignId('approved_by_user_id')
                ->nullable()
                ->after('approval_status')
                ->constrained('users')
                ->nullOnDelete()
                ->comment('User who approved this expense');

            $table->timestamp('approved_at')
                ->nullable()
                ->after('approved_by_user_id')
                ->comment('When the expense was approved');

            $table->text('approval_notes')
                ->nullable()
                ->after('approved_at')
                ->comment('Notes from the approver');

            // Index for common queries
            $table->index(['company_id', 'affects_profit'], 'idx_expenses_profit');
            $table->index(['company_id', 'reduces_capital'], 'idx_expenses_capital');
            $table->index(['company_id', 'is_locked'], 'idx_expenses_locked');
            $table->index(['company_id', 'approval_status'], 'idx_expenses_approval');
        });
    }

    public function down(): void
    {
        Schema::table('expenses', function (Blueprint $table) {
            $table->dropForeign(['financial_operation_id']);

            $table->dropIndex('idx_expenses_profit');
            $table->dropIndex('idx_expenses_capital');
            $table->dropIndex('idx_expenses_locked');
            $table->dropIndex('idx_expenses_approval');

            $table->dropForeign(['approved_by_user_id']);

            $table->dropColumn([
                'affects_profit',
                'reduces_capital',
                'is_locked',
                'locked_at',
                'lock_reason',
                'requires_approval',
                'approval_status',
                'approved_by_user_id',
                'approved_at',
                'approval_notes',
            ]);
        });
    }
};
