<?php

namespace Autogedal\TbiBank\Model;

/** Formats human-readable TBI callback messages for order history. */
class CallbackAudit
{
    public const COMMAND_UPDATE_STATUS = 'update_status';
    public const COMMAND_FAILURE_REDIRECT = 'failure_redirect';

    public static function statusCodeFor(string $tbiStatus): ?string
    {
        return match (strtolower(trim($tbiStatus))) {
            'canceled', 'cancelled' => '0',
            'approved' => '1',
            'in progress' => '2',
            'rejected' => '3',
            default => null,
        };
    }

    public static function comment(
        string $command,
        string $tbiStatus,
        ?string $statusCode = null,
        ?string $contractId = null,
        ?string $message = null,
        ?string $motive = null
    ): string {
        if ($command === self::COMMAND_FAILURE_REDIRECT) {
            return 'TBI Bank: cererea de finanțare nu a fost finalizată. '
                . 'Clientul a revenit pe site fără aprobarea finanțării. '
                . 'Comanda nu poate fi procesată prin plata în rate TBI Bank.';
        }

        if ($statusCode === '0') {
            $comment = 'TBI Bank: finanțarea a fost anulată. '
                . 'Comanda nu poate fi procesată prin plata în rate TBI Bank.';
            return self::appendDetails($comment, $message, $motive);
        }

        if ($statusCode === '3') {
            $comment = 'TBI Bank: cererea de finanțare a fost respinsă. '
                . 'Comanda nu poate fi procesată prin plata în rate TBI Bank.';
            return self::appendDetails($comment, $message, $motive);
        }

        if (self::statusCodeFor($tbiStatus) === '1' || $statusCode === '1') {
            $comment = 'TBI Bank: finanțarea a fost aprobată și plata a fost înregistrată în Magento.';
            if ($contractId !== null && $contractId !== '') {
                $comment .= ' Contract TBI: ' . $contractId . '.';
            }
            return self::appendDetails($comment, $message, $motive);
        }

        return 'TBI Bank: statusul finanțării a fost actualizat la „' . $tbiStatus . '”.';
    }

    private static function appendDetails(string $comment, ?string $message, ?string $motive): string
    {
        if ($message !== null && trim($message) !== '') {
            $comment .= ' Mesaj TBI: ' . trim($message) . '.';
        }
        if ($motive !== null && trim($motive) !== '') {
            $comment .= ' Motiv TBI: ' . trim($motive) . '.';
        }
        return $comment;
    }
}
