<?php

declare(strict_types=1);

namespace App\DTOs;

use App\Models\Credit;
use App\Models\CreditRestructureLog;
use App\Models\FinancialOperation;
use App\ValueObjects\Money;

/**
 * DTO inmutable con el resultado de una operación de crédito.
 * Contiene todas las entidades creadas y los valores calculados.
 */
readonly class CreditOperationResult
{
    public function __construct(
        public Credit $originalCredit,
        public Credit $newCredit,
        public CreditRestructureLog $restructureLog,
        public FinancialOperation $financialOperation,
        public Money $previousBalance,
        public Money $newPrincipal,
        public Money $cashOut,
        public Money $compensatedAmount,
        public string $operationType,
    ) {}

    /**
     * Convierte a array para respuestas API o logging.
     */
    public function toArray(): array
    {
        return [
            'operation_type' => $this->operationType,
            'original_credit_id' => $this->originalCredit->id,
            'original_credit_status' => $this->originalCredit->status,
            'new_credit_id' => $this->newCredit->id,
            'new_credit_status' => $this->newCredit->status,
            'restructure_log_id' => $this->restructureLog->id,
            'financial_operation_id' => $this->financialOperation->id,
            'financial_summary' => [
                'previous_balance' => $this->previousBalance->value(),
                'new_principal' => $this->newPrincipal->value(),
                'cash_out' => $this->cashOut->value(),
                'compensated_amount' => $this->compensatedAmount->value(),
            ],
        ];
    }

    /**
     * Genera mensaje descriptivo de la operación.
     */
    public function getSummaryMessage(): string
    {
        $typeLabel = match ($this->operationType) {
            'extension' => 'Extensión',
            'extension_with_interest' => 'Prórroga con Réditos',
            'refinance' => 'Refinanciación',
            'restructure' => 'Reestructuración',
            'renewal' => 'Renovación',
            default => ucfirst($this->operationType),
        };

        return sprintf(
            '%s completada. Crédito #%d → #%d. Saldo anterior: %s, Nuevo principal: %s, Desembolso: %s',
            $typeLabel,
            $this->originalCredit->id,
            $this->newCredit->id,
            $this->previousBalance->formatWithCurrency(),
            $this->newPrincipal->formatWithCurrency(),
            $this->cashOut->formatWithCurrency(),
        );
    }
}
