using AutoMapper;
using BookHive.DTO.Author;
using BookHive.DTO.Book;
using BookHive.DTO.Loan;
using BookHive.DTO.Member;
using BookHive.DTO.Review;
using BookHive.Models;

namespace BookHive.MappingProfiles;

public class EntityToDtoMappings : Profile
{
    public EntityToDtoMappings()
    {
        CreateMap<Book, GetBookDto>()
            .ForMember(
                dest => dest.AuthorFullName,
                opt =>
                    opt.MapFrom(src =>
                        src.Author!.FirstName + " " + src.Author.LastName)
            );
        CreateMap<Book, GetBookDetailsDto>()
            .ForMember(
                dest => dest.AverageRating,
                opt => opt.MapFrom(src => src.Reviews.Any() ? src.Reviews.Average(r => r.Rating) : 0)
            )
            .ForMember(
                dest => dest.ReviewCount,
                opt => opt.MapFrom(src => src.Reviews.Count)
            );

        CreateMap<Author, GetAuthorDto>();
        CreateMap<Author, GetAuthorDetailsDto>();

        CreateMap<Loan, GetLoanDto>()
            .ForMember(
                dest => dest.BookTitle,
                opt =>
                    opt.MapFrom(src => src.Book!.Title))
            .ForMember(
                dest => dest.MemberFullName,
                opt =>
                    opt.MapFrom(src => src.Member!.FirstName + ' ' + src.Member!.LastName));

        CreateMap<Member, GetMemberDto>();
        CreateMap<Member, GetMemberDetailsDto>();

        CreateMap<Review, GetReviewDto>()
            .ForMember(
                dest => dest.BookTitle,
                opt =>
                    opt.MapFrom(src => src.Book!.Title))
            .ForMember(
                dest => dest.MemberFullName,
                opt =>
                    opt.MapFrom(src => src.Member!.FirstName + ' ' + src.Member!.LastName));
    }
}