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

namespace IamService.API.Application.Commands.UserProfiles;

/// <summary>
/// EN: Handler for UpdateUserProfileCommand.
/// VI: Handler cho UpdateUserProfileCommand.
/// </summary>
public class UpdateUserProfileCommandHandler 
    : IRequestHandler<UpdateUserProfileCommand, UpdateUserProfileCommandResult>
{
    private readonly IamServiceContext _context;
    private readonly ILogger<UpdateUserProfileCommandHandler> _logger;

    public UpdateUserProfileCommandHandler(
        IamServiceContext context,
        ILogger<UpdateUserProfileCommandHandler> logger)
    {
        _context = context;
        _logger = logger;
    }

    public async Task<UpdateUserProfileCommandResult> Handle(
        UpdateUserProfileCommand request,
        CancellationToken cancellationToken)
    {
        _logger.LogInformation("Updating profile for user: {UserId}", request.UserId);

        // EN: Get or create user profile
        // VI: Lấy hoặc tạo user profile
        var profile = await _context.UserProfiles
            .FirstOrDefaultAsync(p => EF.Property<Guid>(p, "_userId") == request.UserId, cancellationToken);

        if (profile == null)
        {
            // EN: Create new profile
            // VI: Tạo profile mới
            profile = UserProfile.Create(request.UserId);
            _context.UserProfiles.Add(profile);
        }

        // EN: Update profile information
        // VI: Cập nhật thông tin profile
        profile.UpdateBasicInfo(request.Bio, request.Timezone, request.Locale);

        if (request.AvatarUrl != null)
        {
            profile.SetAvatar(request.AvatarUrl);
        }

        await _context.SaveChangesAsync(cancellationToken);

        _logger.LogInformation("Profile updated for user {UserId}", request.UserId);

        return new UpdateUserProfileCommandResult(
            profile.Id,
            profile.UserId,
            profile.Bio,
            profile.Timezone,
            profile.Locale,
            profile.AvatarUrl,
            profile.UpdatedAt);
    }
}
