// EN: Handler for SendVerificationEmailCommand
// VI: Handler cho SendVerificationEmailCommand

using MediatR;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Logging;
using IamService.Domain.AggregatesModel.UserAggregate;
using IamService.Infrastructure.Email;

namespace IamService.API.Application.Commands.Auth;

/// <summary>
/// EN: Handler for SendVerificationEmailCommand.
/// VI: Handler cho SendVerificationEmailCommand.
/// </summary>
public class SendVerificationEmailCommandHandler : IRequestHandler<SendVerificationEmailCommand, SendVerificationEmailResult>
{
    private readonly UserManager<ApplicationUser> _userManager;
    private readonly IEmailService _emailService;
    private readonly ILogger<SendVerificationEmailCommandHandler> _logger;

    public SendVerificationEmailCommandHandler(
        UserManager<ApplicationUser> userManager,
        IEmailService emailService,
        ILogger<SendVerificationEmailCommandHandler> logger)
    {
        _userManager = userManager;
        _emailService = emailService;
        _logger = logger;
    }

    public async Task<SendVerificationEmailResult> Handle(
        SendVerificationEmailCommand request,
        CancellationToken cancellationToken)
    {
        _logger.LogInformation("Sending verification email to {Email}", request.Email);

        // EN: Find user by email
        // VI: Tìm user theo email
        var user = await _userManager.FindByEmailAsync(request.Email);
        if (user == null)
        {
            _logger.LogWarning("User not found with email {Email}", request.Email);
            // EN: Return success to prevent email enumeration attacks
            // VI: Trả về success để ngăn tấn công liệt kê email
            return new SendVerificationEmailResult(true, "If the email exists, a verification link has been sent.");
        }

        // EN: Check if email is already confirmed
        // VI: Kiểm tra xem email đã được xác nhận chưa
        if (user.EmailConfirmed)
        {
            _logger.LogInformation("Email {Email} is already confirmed", request.Email);
            return new SendVerificationEmailResult(true, "Email is already verified.");
        }

        // EN: Generate email confirmation token
        // VI: Tạo token xác nhận email
        var token = await _userManager.GenerateEmailConfirmationTokenAsync(user);

        // EN: Send verification email
        // VI: Gửi email xác thực
        await _emailService.SendVerificationEmailAsync(request.Email, token, cancellationToken);

        _logger.LogInformation("Verification email sent to {Email}", request.Email);

        return new SendVerificationEmailResult(true, "Verification email sent successfully.");
    }
}
