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

namespace DoliMiddlewareApi.Mappers;

public static class ClientMapper
{
    private static string ResolveRole(string? client, string? fournisseur)
    {
        var isClient   = client      is "1" or "2" or "3";
        var isSupplier = fournisseur is "1";
        return (isClient, isSupplier) switch
        {
            (true,  true)  => "both",
            (false, true)  => "supplier",
            _              => "client"
        };
    }

    public static ClientDto MapToClientDto(ClientResponse clientResponse, List<ContactDto> contacts)
    {
        var clientId = int.TryParse(clientResponse.id, out int id) ? id : 0;

        return new ClientDto
        {
            Id = clientId,
            Name = clientResponse.name,
            CodeClient = clientResponse.code_client,
            TypentCode = clientResponse.typent_code,
            Role = ResolveRole(clientResponse.client, clientResponse.fournisseur),
            Status = clientResponse.status,
            Email = clientResponse.email,
            Phone = clientResponse.phone,
            Contacts = contacts.Where(c => c.ClientId == clientId).ToList()
        };
    }

    public static ClientDto MapToClientDtoWithoutContacts(ClientResponse clientResponse)
    {
        return new ClientDto
        {
            Id = int.TryParse(clientResponse.id, out int id) ? id : 0,
            Name = clientResponse.name,
            CodeClient = clientResponse.code_client,
            TypentCode = clientResponse.typent_code,
            Role = ResolveRole(clientResponse.client, clientResponse.fournisseur),
            Status = clientResponse.status,
            Email = clientResponse.email,
            Phone = clientResponse.phone
        };
    }

    public static ClientDetailDto MapToClientDetailDto(ClientResponse r, List<ContactDto> contacts)
    {
        var clientId = int.TryParse(r.id, out int id) ? id : 0;

        return new ClientDetailDto
        {
            Id = clientId,
            Name = r.name ?? "",
            CodeClient = r.code_client,
            TypentCode = r.typent_code,
            Role = ResolveRole(r.client, r.fournisseur),
            Status = r.status,
            Email = r.email,
            Phone = r.phone,
            Address = r.address,
            Town = r.town,
            Zip = r.zip,
            CountryCode = r.country_code,
            VatNumber = r.tva_intra,
            Url = r.url,
            NotePublic = r.note_public,
            NotePrivate = r.note_private,
            Contacts = contacts.Where(c => c.ClientId == clientId).ToList()
        };
    }
}