using System.Globalization;
using DoliMiddlewareApi.Dtos;
using DoliMiddlewareApi.Dtos.Dolibarr;

namespace DoliMiddlewareApi.Mappers;

public static class SupplierInvoiceMapper
{
    public static SupplierInvoiceDto MapToDto(SupplierInvoiceResponse r)
    {
        return new SupplierInvoiceDto
        {
            Id = int.TryParse(r.id, out int id) ? id : 0,
            Number = r.@ref ?? "SIN-REF",
            SupplierRef = r.ref_supplier,

            Date = r.date.HasValue
                ? DateTimeOffset.FromUnixTimeSeconds(r.date.Value).DateTime
                : null,
            ExpireDate = r.date_lim_reglement.HasValue
                ? DateTimeOffset.FromUnixTimeSeconds(r.date_lim_reglement.Value).DateTime
                : null,

            SupplierId = int.TryParse(r.socid, out int supplierId) ? supplierId : 0,

            TotalHt = Parse(r.total_ht),
            TotalTax = Parse(r.total_tva),
            Total = Parse(r.total_ttc),
            RemainToPay = Parse(r.remaintopay),

            Status = ConvertStatus(r.statut),
            NotePublic = r.note_public,
            NotePrivate = r.note_private
        };
    }

    public static SupplierInvoiceDetailDto MapToDetailDto(SupplierInvoiceDetailResponse r)
    {
        var base_ = MapToDto(r);
        return new SupplierInvoiceDetailDto
        {
            Id = base_.Id,
            Number = base_.Number,
            SupplierRef = base_.SupplierRef,
            Date = base_.Date,
            ExpireDate = base_.ExpireDate,
            SupplierId = base_.SupplierId,
            TotalHt = base_.TotalHt,
            TotalTax = base_.TotalTax,
            Total = base_.Total,
            RemainToPay = base_.RemainToPay,
            Status = base_.Status,
            NotePublic = base_.NotePublic,
            NotePrivate = base_.NotePrivate,
            Lines = r.Lines?.Select(InvoiceMapper.MapToInvoiceLineDto).ToList() ?? []
        };
    }

    private static decimal? Parse(string? value) =>
        decimal.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out decimal d)
            ? Math.Round(d, 2)
            : null;

    private static string ConvertStatus(string? statut) => statut switch
    {
        "0" => "draft",
        "1" => "unpaid",
        "2" => "paid",
        "3" => "cancelled",
        _ => "unknown"
    };
}
