using AutoMapper;
using Lada.Framework.Data.Domains.Identity;
using Lada.Framework.Infrastructures.Helpers;
using Ladaer.BackEnd.Infrastructures.DTO.Items.Identity;
using Ladaer.BackEnd.Infrastructures.DTO.Models.Itentity;
using Ladaer.BackEnd.Infrastructures.DTO.Models.Users;

namespace Ladaer.BackEnd.Infrastructures.DTO.Profiles
{
    public class IdentityMappingProfile : Profile
    {
        public IdentityMappingProfile()
        {
            // User mappings
            CreateMap<User, UserOptionItem>();
            CreateMap<User, StaffItem>()
                .ForMember(dest => dest.CreatedTime, opt => opt.MapFrom(src => src.CreatedTime.ToString("dd/MM/yyyy HH:mm")))
                .ForMember(dest => dest.UpdatedTime, opt => opt.MapFrom(src => src.UpdatedTime.ToString("dd/MM/yyyy HH:mm")))
                .ForMember(dest => dest.PermissionId, opt => opt.MapFrom(src => (src.Permission != null && src.Permission.Id > 0) ? src.Permission.Id : 0))
                .ForMember(dest => dest.PermissionName, opt => opt.MapFrom(src => (src.Permission != null && src.Permission.Id > 0) ? src.Permission.Name : ""))
                .ForMember(dest => dest.PermissionDescription, opt => opt.MapFrom(src => (src.Permission != null && src.Permission.Id > 0) ? src.Permission.Description : ""))
                .ForMember(dest => dest.UserType, opt => opt.MapFrom(src => src.UserType.GetDescription()))
                .ForMember(dest => dest.IsLocked,
                            opt => opt.MapFrom(src => src.LockoutEnabled && src.LockoutEnd.HasValue && src.LockoutEnd.Value > DateTimeOffset.Now));
            CreateMap<User, StaffModel>();

            // Role mappings
            CreateMap<Role, RoleItem>()
                .ForMember(dest => dest.CreatedTime, opt => opt.MapFrom(src => src.CreatedTime.ToString("dd/MM/yyyy HH:mm")))
                .ForMember(dest => dest.UpdatedTime, opt => opt.MapFrom(src => src.UpdatedTime.ToString("dd/MM/yyyy HH:mm")))
                .ForMember(dest => dest.CreatedBy, opt => opt.MapFrom(src => src.CreatedByUserName))
                .ForMember(dest => dest.UpdatedBy, opt => opt.MapFrom(src => src.UpdatedByUserName));
            CreateMap<Role, RoleModel>();
        }
    }

    public static class IdentityMappingExtensions
    {
        // User extensions
        public static UserOptionItem ToOptionItem(this User entity)
            => entity.MapTo<User, UserOptionItem>();

        public static StaffItem ToStaffItem(this User entity)
            => entity.MapTo<User, StaffItem>();

        public static StaffModel ToStaffModel(this User entity)
            => entity.MapTo<User, StaffModel>();

        // Role extensions
        public static RoleItem ToItem(this Role entity)
            => entity.MapTo<Role, RoleItem>();

        public static RoleModel ToModel(this Role entity)
            => entity.MapTo<Role, RoleModel>();
    }
}