<?php

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

return new class extends Migration {
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('loans', function (Blueprint $table) {
            $table->id();
            // Identity
            $table->uuid('idempotency_key')->unique();
            $table->foreignId('user_id')->constrained()->cascadeOnDelete();
            $table->foreignId('account_id')->constrained()->cascadeOnDelete();

            // Loan details
            $table->decimal('amount', 15, 2);
            $table->integer('duration'); // months
            $table->string('credit_facility');
            $table->text('purpose')->nullable();

            // Financial calculations
            $table->decimal('interest_rate', 8, 6);
            $table->decimal('total_interest', 15, 2);
            $table->decimal('monthly_repayment', 15, 2);

            // Outstanding tracking (CRITICAL)
            $table->decimal('principal_outstanding', 15, 2);
            $table->decimal('interest_outstanding', 15, 2);
            $table->decimal('penalty_outstanding', 15, 2)->default(0);
            $table->decimal('total_paid', 15, 2)->default(0);

            // Status lifecycle
            $table->enum('status', [
                'pending',
                'approved',
                'overdue',
                'completed',
                'defaulted',
                'rejected'
            ])->default('pending');

            // Dates
            $table->timestamp('approved_at')->nullable();
            $table->timestamp('rejected_at')->nullable();
            $table->timestamp('completed_at')->nullable();
            $table->date('first_due_date')->nullable();
            $table->date('last_due_date')->nullable();

            // Settings
            $table->boolean('auto_debit_enabled')->default(false);
            $table->integer('grace_period_days')->default(3);

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

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('loans');
    }
};
