<?php

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

/**
 * Phase 1: Enhance incomes table for proper accounting.
 *
 * Adds columns to track:
 * - Whether income affects capital (e.g., principal recovery)
 * - Whether income affects profit (e.g., interest income)
 * - Locking mechanism for financial integrity
 *
 * ACCOUNTING RULES:
 * - loan_payment_principal: affects_capital=true, affects_profit=false
 * - loan_payment_interest: affects_capital=false, affects_profit=true
 * - capital_injection: affects_capital=true, affects_profit=false
 * - late_fee/penalty_interest: affects_capital=false, affects_profit=true
 */
return new class extends Migration
{
    public function up(): void
    {
        Schema::table('incomes', function (Blueprint $table) {
            // Financial impact flags
            $table->boolean('affects_capital')
                ->default(false)
                ->after('metadata')
                ->comment('True if income affects working capital (e.g., principal recovery)');

            $table->boolean('affects_profit')
                ->default(true)
                ->after('affects_capital')
                ->comment('True if income affects P&L (e.g., interest, fees)');

            // Locking mechanism for financial integrity
            $table->boolean('is_locked')
                ->default(false)
                ->after('affects_profit')
                ->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)');

            // Index for common queries
            $table->index(['company_id', 'affects_capital'], 'idx_incomes_capital');
            $table->index(['company_id', 'affects_profit'], 'idx_incomes_profit');
            $table->index(['company_id', 'is_locked'], 'idx_incomes_locked');
        });
    }

    public function down(): void
    {
        Schema::table('incomes', function (Blueprint $table) {
            $table->dropIndex('idx_incomes_capital');
            $table->dropIndex('idx_incomes_profit');
            $table->dropIndex('idx_incomes_locked');

            $table->dropColumn([
                'affects_capital',
                'affects_profit',
                'is_locked',
                'locked_at',
                'lock_reason',
            ]);
        });
    }
};
