using AutoMapper;
using PowderCoating.Core.Entities;
using PowderCoating.Core.Enums;
using PowderCoating.Application.DTOs.Equipment;

namespace PowderCoating.Application.Mappings;

public class EquipmentProfile : Profile
{
    public EquipmentProfile()
    {
        // Equipment to EquipmentDto
        CreateMap<Equipment, EquipmentDto>()
            .ForMember(dest => dest.Status,
                      opt => opt.MapFrom(src => src.Status.ToString()))
            .ForMember(dest => dest.StatusDisplay,
                      opt => opt.MapFrom(src => FormatEnumName(src.Status.ToString())))
            .ForMember(dest => dest.DaysUntilMaintenance,
                      opt => opt.MapFrom(src => src.NextScheduledMaintenance.HasValue
                          ? (int?)(src.NextScheduledMaintenance.Value - DateTime.Now).TotalDays
                          : null));

        // CreateEquipmentDto to Equipment
        CreateMap<CreateEquipmentDto, Equipment>()
            .ForMember(dest => dest.Status,
                      opt => opt.MapFrom(src => Enum.Parse<EquipmentStatus>(src.Status)));

        // UpdateEquipmentDto to Equipment
        CreateMap<UpdateEquipmentDto, Equipment>()
            .ForMember(dest => dest.Status,
                      opt => opt.MapFrom(src => Enum.Parse<EquipmentStatus>(src.Status)));

        // Equipment to UpdateEquipmentDto (needed for Edit GET action)
        CreateMap<Equipment, UpdateEquipmentDto>()
            .ForMember(dest => dest.Status,
                      opt => opt.MapFrom(src => src.Status.ToString()));

        // Equipment to EquipmentListDto
        CreateMap<Equipment, EquipmentListDto>()
            .ForMember(dest => dest.Status,
                      opt => opt.MapFrom(src => src.Status.ToString()))
            .ForMember(dest => dest.StatusDisplay,
                      opt => opt.MapFrom(src => FormatEnumName(src.Status.ToString())));
    }

    private static string FormatEnumName(string enumName)
    {
        // Convert "NeedsMaintenance" to "Needs Maintenance"
        return System.Text.RegularExpressions.Regex.Replace(enumName, "([a-z])([A-Z])", "$1 $2");
    }
}
