using AutoMapper;
using PowderCoating.Core.Entities;
using PowderCoating.Application.DTOs.Customer;

namespace PowderCoating.Application.Mappings;

public class CustomerProfile : Profile
{
    public CustomerProfile()
    {
        // Customer to CustomerDto
        CreateMap<Customer, CustomerDto>()
            .ForMember(dest => dest.PricingTierName,
                      opt => opt.MapFrom(src => src.PricingTier != null ? src.PricingTier.TierName : null))
            .ForMember(dest => dest.HasTaxExemptCertificate,
                      opt => opt.MapFrom(src => src.TaxExemptCertificateData != null && src.TaxExemptCertificateData.Length > 0));

        // CreateCustomerDto to Customer (SmsConsentGranted is a form-only flag — no entity field)
        CreateMap<CreateCustomerDto, Customer>()
            .ForMember(dest => dest.NotifyBySms, opt => opt.Ignore())   // controller sets this after consent check
            .ForMember(dest => dest.SmsConsentedAt, opt => opt.Ignore())
            .ForMember(dest => dest.SmsConsentMethod, opt => opt.Ignore());

        // UpdateCustomerDto to Customer
        CreateMap<UpdateCustomerDto, Customer>()
            .ForMember(dest => dest.TaxExemptCertificateData, opt => opt.Ignore())
            .ForMember(dest => dest.TaxExemptCertificateContentType, opt => opt.Ignore())
            .ForMember(dest => dest.TaxExemptCertificateFileName, opt => opt.Ignore())
            .ForMember(dest => dest.SmsConsentedAt, opt => opt.Ignore())    // controller manages
            .ForMember(dest => dest.SmsConsentMethod, opt => opt.Ignore()); // controller manages

        // Customer to UpdateCustomerDto (needed for Edit GET action)
        CreateMap<Customer, UpdateCustomerDto>()
            .ForMember(dest => dest.HasTaxExemptCertificate,
                      opt => opt.MapFrom(src => src.TaxExemptCertificateData != null && src.TaxExemptCertificateData.Length > 0))
            .ForMember(dest => dest.SmsConsentGranted, opt => opt.Ignore()); // form-only, always starts unchecked

        // Customer to CustomerListDto
        CreateMap<Customer, CustomerListDto>()
            .ForMember(dest => dest.ContactName,
                      opt => opt.MapFrom(src => !string.IsNullOrEmpty(src.ContactFirstName) || !string.IsNullOrEmpty(src.ContactLastName)
                          ? $"{src.ContactFirstName} {src.ContactLastName}".Trim()
                          : string.Empty));

        // CustomerContact
        CreateMap<CustomerContact, CustomerContactDto>();
        CreateMap<CreateCustomerContactDto, CustomerContact>();
        CreateMap<UpdateCustomerContactDto, CustomerContact>()
            .ForMember(dest => dest.Id, opt => opt.Ignore()); // Id is set by the controller, not mapped
        CreateMap<CustomerContact, UpdateCustomerContactDto>();
    }
}
