using CMSMicroservice.Application.Common.Interfaces;

namespace CMSMicroservice.Application.UserCQ.Queries.GetCustomerProfile;

public class GetCustomerProfileQueryHandler : IRequestHandler<GetCustomerProfileQuery, GetCustomerProfileResponseDto>
{
    private readonly IApplicationDbContext _context;
    private readonly ICurrentUserService _currentUser;

    public GetCustomerProfileQueryHandler(IApplicationDbContext context, ICurrentUserService currentUser)
    {
        _context = context;
        _currentUser = currentUser;
    }

    public async Task<GetCustomerProfileResponseDto> Handle(GetCustomerProfileQuery request, CancellationToken cancellationToken)
    {
        // Get userId from ICurrentUserService if not provided
        var userId = request.UserId == 0
            ? (long.TryParse(_currentUser.UserId, out var id) ? id : 0)
            : request.UserId;

        if (userId == 0)
            throw new UnauthorizedAccessException("User ID not found in JWT token");

        var user = await _context.Users
            .AsNoTracking()
            .Where(x => x.Id == userId)
            .FirstOrDefaultAsync(cancellationToken);

        if (user == null)
            throw new NotFoundException(nameof(User), userId);

        var fullName = $"{user.FirstName} {user.LastName}".Trim();
        var profileCompletionPercentage = CalculateProfileCompletion(user);

        return new GetCustomerProfileResponseDto
        {
            Id = user.Id,
            FirstName = user.FirstName,
            LastName = user.LastName,
            Mobile = user.Mobile,
            Email = user.Email,
            NationalCode = user.NationalCode,
            AvatarPath = user.AvatarPath,
            ParentId = user.NetworkParentId,
            ReferralCode = user.ReferralCode,
            IsMobileVerified = user.IsMobileVerified,
            MobileVerifiedAt = user.MobileVerifiedAt,
            EmailNotifications = user.EmailNotifications,
            SmsNotifications = user.SmsNotifications,
            PushNotifications = user.PushNotifications,
            BirthDate = user.BirthDate,
            FullName = fullName,
            ProfileCompletionPercentage = profileCompletionPercentage
        };
    }

    private int CalculateProfileCompletion(Domain.Entities.User user)
    {
        var totalFields = 10;
        var completedFields = 0;

        if (!string.IsNullOrEmpty(user.FirstName)) completedFields++;
        if (!string.IsNullOrEmpty(user.LastName)) completedFields++;
        if (!string.IsNullOrEmpty(user.Mobile)) completedFields++;
        if (!string.IsNullOrEmpty(user.Email)) completedFields++;
        if (!string.IsNullOrEmpty(user.NationalCode)) completedFields++;
        if (!string.IsNullOrEmpty(user.AvatarPath)) completedFields++;
        if (user.BirthDate.HasValue) completedFields++;
        if (user.IsMobileVerified) completedFields++;
        if (user.NetworkParentId.HasValue) completedFields++;
        if (!string.IsNullOrEmpty(user.ReferralCode)) completedFields++;

        return (int)((double)completedFields / totalFields * 100);
    }
}
