using MediatR;
using Microsoft.EntityFrameworkCore;
using IamService.Domain.AggregatesModel.UserAggregate;
using IamService.Infrastructure;

namespace IamService.API.Application.Queries.UserProfiles;

/// <summary>
/// EN: Handler for GetUserProfileQuery.
/// VI: Handler cho GetUserProfileQuery.
/// </summary>
public class GetUserProfileQueryHandler : IRequestHandler<GetUserProfileQuery, UserProfileDto?>
{
    private readonly IamServiceContext _context;

    public GetUserProfileQueryHandler(IamServiceContext context)
    {
        _context = context;
    }

    public async Task<UserProfileDto?> Handle(GetUserProfileQuery request, CancellationToken cancellationToken)
    {
        var profile = await _context.UserProfiles
            .Include(p => p.Attributes)
            .FirstOrDefaultAsync(p => EF.Property<Guid>(p, "_userId") == request.UserId, cancellationToken);

        if (profile == null)
            return null;

        return MapToDto(profile);
    }

    private static UserProfileDto MapToDto(UserProfile profile)
    {
        return new UserProfileDto(
            profile.Id,
            profile.UserId,
            profile.Bio,
            profile.AvatarUrl,
            profile.Timezone,
            profile.Locale,
            profile.DateOfBirth,
            profile.PhoneNumber != null 
                ? new PhoneNumberDto(profile.PhoneNumber.CountryCode, profile.PhoneNumber.NationalNumber) 
                : null,
            profile.Address != null
                ? new AddressDto(
                    profile.Address.Street,
                    profile.Address.Street2,
                    profile.Address.City,
                    profile.Address.State,
                    profile.Address.PostalCode,
                    profile.Address.Country)
                : null,
            profile.Attributes.Select(a => new ProfileAttributeDto(
                a.Key,
                a.Value,
                a.ValueType?.Name ?? "String")),
            profile.CreatedAt,
            profile.UpdatedAt);
    }
}
