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

namespace PowderCoating.Application.Mappings;

public class InventoryProfile : Profile
{
    public InventoryProfile()
    {
        // InventoryItem to InventoryItemDto
        CreateMap<InventoryItem, InventoryItemDto>()
            .ForMember(dest => dest.CategoryName,
                      opt => opt.MapFrom(src => src.InventoryCategory != null ? src.InventoryCategory.DisplayName : null))
            .ForMember(dest => dest.PrimaryVendorName,
                      opt => opt.MapFrom(src => src.PrimaryVendor != null ? src.PrimaryVendor.CompanyName : null))
            .ForMember(dest => dest.IsLowStock,
                      opt => opt.MapFrom(src => src.QuantityOnHand > 0 && src.QuantityOnHand <= src.ReorderPoint))
            .ForMember(dest => dest.IsOutOfStock,
                      opt => opt.MapFrom(src => src.QuantityOnHand <= 0))
            .ForMember(dest => dest.InventoryAccountName,
                      opt => opt.MapFrom(src => src.InventoryAccount != null
                          ? $"{src.InventoryAccount.AccountNumber} – {src.InventoryAccount.Name}" : null))
            .ForMember(dest => dest.CogsAccountName,
                      opt => opt.MapFrom(src => src.CogsAccount != null
                          ? $"{src.CogsAccount.AccountNumber} – {src.CogsAccount.Name}" : null));

        // CreateInventoryItemDto to InventoryItem
        CreateMap<CreateInventoryItemDto, InventoryItem>()
            .ForMember(dest => dest.AverageCost, opt => opt.MapFrom(src => src.UnitCost))
            .ForMember(dest => dest.LastPurchasePrice, opt => opt.MapFrom(src => src.UnitCost))
            .ForMember(dest => dest.InventoryAccount, opt => opt.Ignore())
            .ForMember(dest => dest.CogsAccount, opt => opt.Ignore());

        // UpdateInventoryItemDto to InventoryItem
        CreateMap<UpdateInventoryItemDto, InventoryItem>()
            .ForMember(dest => dest.InventoryAccount, opt => opt.Ignore())
            .ForMember(dest => dest.CogsAccount, opt => opt.Ignore());

        // InventoryItem to UpdateInventoryItemDto (needed for Edit GET action)
        CreateMap<InventoryItem, UpdateInventoryItemDto>();

        // InventoryItem to InventoryListDto
        CreateMap<InventoryItem, InventoryListDto>()
            .ForMember(dest => dest.CategoryName,
                      opt => opt.MapFrom(src => src.InventoryCategory != null ? src.InventoryCategory.DisplayName : null))
            .ForMember(dest => dest.PrimaryVendorName,
                      opt => opt.MapFrom(src => src.PrimaryVendor != null ? src.PrimaryVendor.CompanyName : null))
            .ForMember(dest => dest.IsLowStock,
                      opt => opt.MapFrom(src => src.QuantityOnHand > 0 && src.QuantityOnHand <= src.ReorderPoint))
            .ForMember(dest => dest.IsOutOfStock,
                      opt => opt.MapFrom(src => src.QuantityOnHand <= 0));
    }
}
