using System;

namespace GestionaDenuncias.Shared.Models;

public sealed class ThirdPartyIdentityData
{
    public bool IsAnonymous { get; set; }
    public bool IsLegalEntity { get; set; }
    public string DocumentId { get; set; } = string.Empty;
    public string FirstName { get; set; } = string.Empty;
    public string LastName { get; set; } = string.Empty;
    public string BusinessName { get; set; } = string.Empty;
    public string Email { get; set; } = string.Empty;
    public string CountryCode { get; set; } = string.Empty;
    public ThirdPartyAddressData? Address { get; set; }

    public string DisplayName =>
        IsLegalEntity
            ? BusinessName
            : string.Join(
                ' ',
                new[] { FirstName, LastName }
                    .Where(value => !string.IsNullOrWhiteSpace(value)));

    public static ThirdPartyIdentityData FromComplaint(DenunciasGestiona denuncia)
    {
        ArgumentNullException.ThrowIfNull(denuncia);

        var isAnonymous = denuncia.EsAnonima ||
                          string.Equals(
                              denuncia.DocumentoResuelto?.Trim(),
                              "00000000T",
                              StringComparison.OrdinalIgnoreCase);

        return new ThirdPartyIdentityData
        {
            IsAnonymous = isAnonymous,
            IsLegalEntity = !isAnonymous && denuncia.EsPersonaJuridica,
            DocumentId = isAnonymous
                ? "00000000T"
                : (denuncia.DocumentoResuelto ?? string.Empty).Trim().ToUpperInvariant(),
            FirstName = isAnonymous ? "Anonimo" : denuncia.NombreResuelto.Trim(),
            LastName = isAnonymous ? "-" : BuildLastName(denuncia),
            BusinessName = isAnonymous ? string.Empty : denuncia.RazonSocialResuelta.Trim(),
            Email = (denuncia.Correo_Electronico ?? string.Empty).Trim(),
            CountryCode = string.IsNullOrWhiteSpace(denuncia.Pais) ? denuncia.PaisOrigen : denuncia.Pais,
            Address = isAnonymous ? null : ThirdPartyAddressData.FromComplaint(denuncia)
        };
    }

    private static string BuildLastName(DenunciasGestiona denuncia)
    {
        var separated = string.Join(
            ' ',
            new[] { denuncia.PrimerApellidoResuelto, denuncia.SegundoApellidoResuelto }
                .Where(value => !string.IsNullOrWhiteSpace(value))
                .Select(value => value.Trim()));

        return string.IsNullOrWhiteSpace(separated)
            ? denuncia.ApellidosResueltos.Trim()
            : separated;
    }
}
