// EN: Handler for external login command
// VI: Handler cho command external login
using IamService.Domain.AggregatesModel.UserAggregate;
using IamService.Infrastructure.SocialLogin;
using MediatR;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Logging;

namespace IamService.API.Application.Commands.Auth;

/// <summary>
/// EN: Handler for processing external login from OAuth providers.
/// VI: Handler xử lý external login từ OAuth providers.
/// </summary>
public class ExternalLoginCommandHandler : IRequestHandler<ExternalLoginCommand, ExternalLoginResult>
{
    private readonly ISocialLoginService _socialLoginService;
    private readonly UserManager<ApplicationUser> _userManager;
    private readonly SignInManager<ApplicationUser> _signInManager;
    private readonly ILogger<ExternalLoginCommandHandler> _logger;

    public ExternalLoginCommandHandler(
        ISocialLoginService socialLoginService,
        UserManager<ApplicationUser> userManager,
        SignInManager<ApplicationUser> signInManager,
        ILogger<ExternalLoginCommandHandler> logger)
    {
        _socialLoginService = socialLoginService;
        _userManager = userManager;
        _signInManager = signInManager;
        _logger = logger;
    }

    public async Task<ExternalLoginResult> Handle(ExternalLoginCommand request, CancellationToken cancellationToken)
    {
        _logger.LogInformation(
            "EN: Processing external login for {Provider} / VI: Xử lý external login cho {Provider}",
            request.Provider);

        try
        {
            // EN: Process external login
            // VI: Xử lý external login
            var result = await _socialLoginService.ProcessExternalLoginAsync(
                request.Provider,
                request.ProviderUserId,
                request.Email,
                request.Name,
                request.PictureUrl);

            if (!result.Success || result.User == null)
            {
                _logger.LogWarning(
                    "EN: External login failed: {Error} / VI: External login thất bại: {Error}",
                    result.ErrorMessage);

                return new ExternalLoginResult
                {
                    Success = false,
                    Message = result.ErrorMessage ?? "External login failed"
                };
            }

            // EN: Sign in the user
            // VI: Đăng nhập user
            await _signInManager.SignInAsync(result.User, isPersistent: false);

            _logger.LogInformation(
                "EN: External login successful for user {UserId} / VI: External login thành công cho user {UserId}",
                result.User.Id);

            // EN: Note: Token generation should be handled by the controller
            // VI: Lưu ý: Tạo token nên được xử lý bởi controller
            return new ExternalLoginResult
            {
                Success = true,
                Message = result.IsNewUser 
                    ? "Account created and logged in successfully" 
                    : "Logged in successfully",
                UserId = result.User.Id,
                Email = result.User.Email,
                IsNewUser = result.IsNewUser
            };
        }
        catch (Exception ex)
        {
            _logger.LogError(ex,
                "EN: Error during external login / VI: Lỗi trong quá trình external login");

            return new ExternalLoginResult
            {
                Success = false,
                Message = "An error occurred during external authentication"
            };
        }
    }
}
