<?php

declare(strict_types=1);

namespace App\Console\Commands;

use App\Models\Installment;
use App\Services\Metrics\InterestAttributionService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

/**
 * Verifica la imputacion de interes contra datos reales.
 *
 * Compara el interes derivado del pivote (regla interes-primero) contra el
 * calculado directamente sobre las cuotas — dos caminos independientes que
 * deben dar lo mismo. Para J&A Asociados (company 1) el valor esperado al
 * 2026-09-08 era $50.060.364.
 *
 * No es un test: CI corre con BD limpia. Correr a mano tras cambios en la
 * imputacion o al sospechar de la cobertura del pivote.
 */
class VerifyInterestAttribution extends Command
{
    protected $signature = 'credify:verify-interest {--company=1 : ID de la empresa a verificar}';

    protected $description = 'Compara el interes derivado del pivote contra el calculado por cuotas y reporta la brecha';

    public function handle(InterestAttributionService $service): int
    {
        $companyId = (int) $this->option('company');

        $derivado = $service->interestTotal($companyId);

        // Camino independiente: mismo criterio que interest_earned.
        $row = DB::selectOne('
            SELECT COALESCE(SUM(
                CASE WHEN i.status = ? THEN i.interest_amount
                     ELSE LEAST(i.amount_paid, i.interest_amount) END
            ), 0) AS interes
            FROM installments i
            INNER JOIN credits c ON c.id = i.credit_id
            WHERE c.company_id = ?
        ', [Installment::STATUS_PAID, $companyId]);

        $porCuotas = (float) ($row->interes ?? 0.0);
        $brecha = $derivado - $porCuotas;

        $this->table(['Fuente', 'Interes'], [
            ['Derivado del pivote (interes-primero)', number_format($derivado, 2)],
            ['Calculado por cuotas (independiente)', number_format($porCuotas, 2)],
            ['Brecha', number_format($brecha, 2)],
        ]);

        if (abs($brecha) < 1.0) {
            $this->info('OK: los dos caminos cuadran. La imputacion es fiable.');

            return self::SUCCESS;
        }

        $this->warn(sprintf(
            'Brecha de %s (%.4f%%): hay pagos fuera de payment_installment o cuotas sin aplicaciones.',
            number_format($brecha, 2),
            $porCuotas > 0.0 ? ($brecha / $porCuotas) * 100 : 0.0
        ));

        return self::FAILURE;
    }
}
