<?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::table('businesses', function (Blueprint $table): void {
            $table->string('loan_approval_mode')->default('approval_required');
            $table->boolean('maker_checker_enabled')->default(false);
            $table->decimal('manager_approval_threshold', 18, 2)->nullable();
        });

        Schema::table('loans', function (Blueprint $table): void {
            $table->timestamp('approved_at')->nullable();
            $table->foreignId('approved_by')->nullable()->constrained('users')->nullOnDelete();
        });

        Schema::create('loan_approval_decisions', function (Blueprint $table): void {
            $table->id();
            $table->foreignId('loan_id')->constrained()->restrictOnDelete();
            $table->string('decision');
            $table->string('previous_status');
            $table->string('new_status');
            $table->text('comments')->nullable();
            $table->foreignId('user_id')->nullable()->constrained('users')->nullOnDelete();
            $table->boolean('is_auto')->default(false);
            $table->timestamp('decided_at');
            $table->timestamps();

            $table->index(['loan_id', 'decided_at']);
            $table->index(['decision', 'decided_at']);
        });
    }

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

        Schema::table('loans', function (Blueprint $table): void {
            $table->dropConstrainedForeignId('approved_by');
            $table->dropColumn('approved_at');
        });

        Schema::table('businesses', function (Blueprint $table): void {
            $table->dropColumn(['loan_approval_mode', 'maker_checker_enabled', 'manager_approval_threshold']);
        });
    }
};
