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

namespace Indotalent.Features.Account.ForgotPassword.Cqrs;

public class ForgotPasswordRequest
{
    public string Email { get; set; } = string.Empty;
}

public class ForgotPasswordResponse
{
    public string Message { get; set; } = string.Empty;
}

public record ForgotPasswordCommand(ForgotPasswordRequest Data) : IRequest<ForgotPasswordResponse>;

public class ForgotPasswordHandler : IRequestHandler<ForgotPasswordCommand, ForgotPasswordResponse>
{
    private readonly UserManager<ApplicationUser> _userManager;
    private readonly IEmailSender<ApplicationUser> _emailSender;
    private readonly IHttpContextAccessor _httpContextAccessor;

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

    public async Task<ForgotPasswordResponse> Handle(ForgotPasswordCommand request, CancellationToken cancellationToken)
    {
        var user = await _userManager.FindByEmailAsync(request.Data.Email);

        if (user == null || !(await _userManager.IsEmailConfirmedAsync(user)))
        {
            return new ForgotPasswordResponse { Message = "If your email is registered, you will receive a reset link." };
        }

        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>Password Reset Request</h3>
                <p>Hello, {user.FullName}!</p>
                <p>We received a request to reset your password. Click the link below to proceed:</p>
                <p><a href=""{callbackUrl}"" style=""color: #2196F3; font-weight: bold;"">Reset Password</a></p>
                <br/>
                <p style=""font-size: 0.8em; color: #666;"">If you didn't request this, you can safely ignore this email.</p>
                <p style=""font-size: 0.8em; color: #666;"">{callbackUrl}</p>
            </div>";

        await _emailSender.SendPasswordResetLinkAsync(user, user.Email!, message);

        return new ForgotPasswordResponse { Message = "Reset link has been sent." };
    }
}