using Indotalent.Data.Entities;
using MediatR;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.WebUtilities;
using System.Text;

namespace Indotalent.Features.Setting.SystemUser.Cqrs;

public class AdminForgotPasswordResponse
{
    public bool IsSuccess { get; set; }
    public string Message { get; set; } = string.Empty;
}

public record AdminForgotPasswordCommand(string UserId) : IRequest<AdminForgotPasswordResponse>;

public class AdminForgotPasswordHandler : IRequestHandler<AdminForgotPasswordCommand, AdminForgotPasswordResponse>
{
    private readonly UserManager<ApplicationUser> _userManager;
    private readonly IEmailSender<ApplicationUser> _emailSender;
    private readonly IHttpContextAccessor _httpContextAccessor;

    public AdminForgotPasswordHandler(
        UserManager<ApplicationUser> userManager,
        IEmailSender<ApplicationUser> emailSender,
        IHttpContextAccessor httpContextAccessor)
    {
        _userManager = userManager;
        _emailSender = emailSender;
        _httpContextAccessor = httpContextAccessor;
    }

    public async Task<AdminForgotPasswordResponse> Handle(AdminForgotPasswordCommand request, CancellationToken cancellationToken)
    {
        var user = await _userManager.FindByIdAsync(request.UserId);
        if (user == null) return new AdminForgotPasswordResponse { IsSuccess = false, Message = "User not found" };

        var code = await _userManager.GeneratePasswordResetTokenAsync(user);
        code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));

        var requestHttp = _httpContextAccessor.HttpContext?.Request;
        var scheme = requestHttp?.Scheme ?? "https";
        var host = requestHttp?.Host.Value ?? "localhost:8080";

        var callbackUrl = $"{scheme}://{host}/account/reset-password?userId={user.Id}&code={code}";

        var message = $@"
            <div style=""font-family: Arial, sans-serif;"">
                <h3>System Administrator Password Reset</h3>
                <p>Hello, {user.FullName}!</p>
                <p>An administrator has initiated a password reset for your account. Please click the link below to set your new password:</p>
                <p><a href=""{callbackUrl}"" style=""color: #2196F3; font-weight: bold;"">Reset My Password</a></p>
                <br/>
                <p style=""font-size: 0.8em; color: #666;"">If you believe this is an error, please contact your IT support.</p>
            </div>";

        await _emailSender.SendPasswordResetLinkAsync(user, user.Email!, message);
        return new AdminForgotPasswordResponse
        {
            IsSuccess = true,
            Message = "Reset link sent successfully"
        };
    }
}