using DoliMiddlewareApi.Dtos.Dolibarr;
using DoliMiddlewareApi.Dtos.query;

namespace DoliMiddlewareApi.Mappers;

public static class BankMapper
{
    public static BankAccountDto MapToAccountDto(BankAccountResponse r)
    {
        return new BankAccountDto
        {
            Id            = int.TryParse(r.id, out var id) ? id : 0,
            Label         = r.label ?? r.@ref ?? "Cuenta sin nombre",
            Ref           = r.@ref,
            AccountNumber = r.number,
            Iban          = r.iban_prefix,
            Bic           = r.bic,
            Bank          = r.bank,
            CurrencyCode  = r.currency_code ?? "EUR",
            Balance       = r.solde ?? 0,
            IsClosed      = r.clos == "1",
        };
    }

    public static BankLineDto MapToLineDto(BankLineResponse r, int accountId)
    {
        var lineId = int.TryParse(r.id ?? r.rowid, out var id) ? id : 0;

        DateTime? dateo = r.dateo.HasValue
            ? DateTimeOffset.FromUnixTimeSeconds(r.dateo.Value).DateTime
            : null;

        DateTime? datev = r.datev.HasValue
            ? DateTimeOffset.FromUnixTimeSeconds(r.datev.Value).DateTime
            : null;

        return new BankLineDto
        {
            Id            = lineId,
            Label         = r.label,
            Amount        = r.amount ?? 0,
            Date          = dateo,
            DateValue     = datev,
            AccountId     = int.TryParse(r.fk_account, out var accId) ? accId : accountId,
            BankStatement = r.num_releve,
            Type          = r.type,
        };
    }
}
