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

            // CLAVES DE RELACIÓN
            $table->foreignId('credit_id')->constrained()->cascadeOnDelete();

            // ÍNDICE Y ESTADO
            $table->unsignedInteger('installment_number');
            $table->enum('status', ['pending', 'partial_paid', 'paid', 'overdue'])->default('pending');

            // FECHAS
            $table->date('due_date')->comment('Fecha límite de pago.');
            $table->date('paid_date')->nullable()->comment('Fecha real de pago.');

            // MONTOS DE LA CUOTA
            $table->decimal('principal_amount', 10, 2)->comment('Parte del capital de la cuota.');
            $table->decimal('interest_amount', 10, 2)->comment('Parte del interés de la cuota.');
            $table->decimal('total_amount', 10, 2)->comment('Suma de principal + interés.');
            $table->decimal('balance_due', 10, 2)->comment('Saldo restante del principal después de esta cuota.');

            // CONTROL DE PAGOS
            $table->decimal('amount_paid', 10, 2)->default(0.00)->comment('Monto total abonado a esta cuota.');

            $table->timestamps();

            // Asegurar que solo haya una cuota con el mismo número para un crédito dado
            $table->unique(['credit_id', 'installment_number']);
        });
    }

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