// EN: SMTP email service implementation using MailKit
// VI: Implementation email service sử dụng MailKit

using MailKit.Net.Smtp;
using MailKit.Security;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using MimeKit;

namespace IamService.Infrastructure.Email;

/// <summary>
/// EN: SMTP-based email service implementation using MailKit.
/// VI: Implementation email service dựa trên SMTP sử dụng MailKit.
/// </summary>
public class SmtpEmailService : IEmailService
{
    private readonly EmailSettings _settings;
    private readonly ILogger<SmtpEmailService> _logger;

    public SmtpEmailService(
        IOptions<EmailSettings> settings,
        ILogger<SmtpEmailService> logger)
    {
        _settings = settings.Value;
        _logger = logger;
    }

    /// <inheritdoc />
    public async Task SendEmailAsync(string to, string subject, string htmlBody, CancellationToken cancellationToken = default)
    {
        try
        {
            var message = new MimeMessage();
            message.From.Add(new MailboxAddress(_settings.SenderName, _settings.SenderEmail));
            message.To.Add(MailboxAddress.Parse(to));
            message.Subject = subject;

            var bodyBuilder = new BodyBuilder
            {
                HtmlBody = htmlBody
            };
            message.Body = bodyBuilder.ToMessageBody();

            using var client = new SmtpClient();
            
            await client.ConnectAsync(
                _settings.SmtpServer, 
                _settings.SmtpPort, 
                SecureSocketOptions.StartTls, 
                cancellationToken);
            
            await client.AuthenticateAsync(
                _settings.SmtpLogin, 
                _settings.SmtpPassword, 
                cancellationToken);
            
            await client.SendAsync(message, cancellationToken);
            await client.DisconnectAsync(true, cancellationToken);

            _logger.LogInformation("Email sent successfully to {To}, Subject: {Subject}", to, subject);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to send email to {To}, Subject: {Subject}", to, subject);
            throw;
        }
    }

    /// <inheritdoc />
    public async Task SendVerificationEmailAsync(string email, string token, CancellationToken cancellationToken = default)
    {
        var verificationUrl = $"{_settings.BaseUrl}/api/v1/auth/confirm-email?email={Uri.EscapeDataString(email)}&token={Uri.EscapeDataString(token)}";
        
        var htmlBody = $@"
<!DOCTYPE html>
<html>
<head>
    <meta charset=""utf-8"">
    <title>Email Verification</title>
    <style>
        body {{ font-family: Arial, sans-serif; line-height: 1.6; color: #333; }}
        .container {{ max-width: 600px; margin: 0 auto; padding: 20px; }}
        .header {{ background: #4a90d9; color: white; padding: 20px; text-align: center; }}
        .content {{ padding: 30px; background: #f9f9f9; }}
        .button {{ display: inline-block; padding: 12px 30px; background: #4a90d9; color: white; text-decoration: none; border-radius: 5px; margin: 20px 0; }}
        .footer {{ padding: 20px; text-align: center; font-size: 12px; color: #666; }}
    </style>
</head>
<body>
    <div class=""container"">
        <div class=""header"">
            <h1>Email Verification</h1>
        </div>
        <div class=""content"">
            <p>Hello,</p>
            <p>Thank you for registering. Please click the button below to verify your email address:</p>
            <p style=""text-align: center;"">
                <a href=""{verificationUrl}"" class=""button"">Verify Email</a>
            </p>
            <p>Or copy and paste this link into your browser:</p>
            <p style=""word-break: break-all; font-size: 12px;"">{verificationUrl}</p>
            <p>This link will expire in 24 hours.</p>
            <p>If you did not create an account, please ignore this email.</p>
        </div>
        <div class=""footer"">
            <p>&copy; {DateTime.UtcNow.Year} IAM Service. All rights reserved.</p>
        </div>
    </div>
</body>
</html>";

        await SendEmailAsync(email, "Verify Your Email Address", htmlBody, cancellationToken);
    }

    /// <inheritdoc />
    public async Task Send2FACodeAsync(string email, string code, CancellationToken cancellationToken = default)
    {
        var htmlBody = $@"
<!DOCTYPE html>
<html>
<head>
    <meta charset=""utf-8"">
    <title>2FA Verification Code</title>
    <style>
        body {{ font-family: Arial, sans-serif; line-height: 1.6; color: #333; }}
        .container {{ max-width: 600px; margin: 0 auto; padding: 20px; }}
        .header {{ background: #50c878; color: white; padding: 20px; text-align: center; }}
        .content {{ padding: 30px; background: #f9f9f9; }}
        .code {{ font-size: 32px; font-weight: bold; text-align: center; padding: 20px; background: #fff; border: 2px dashed #50c878; margin: 20px 0; letter-spacing: 8px; }}
        .footer {{ padding: 20px; text-align: center; font-size: 12px; color: #666; }}
    </style>
</head>
<body>
    <div class=""container"">
        <div class=""header"">
            <h1>Two-Factor Authentication</h1>
        </div>
        <div class=""content"">
            <p>Hello,</p>
            <p>Your verification code is:</p>
            <div class=""code"">{code}</div>
            <p>This code will expire in 5 minutes.</p>
            <p>If you did not request this code, please secure your account immediately.</p>
        </div>
        <div class=""footer"">
            <p>&copy; {DateTime.UtcNow.Year} IAM Service. All rights reserved.</p>
        </div>
    </div>
</body>
</html>";

        await SendEmailAsync(email, "Your 2FA Verification Code", htmlBody, cancellationToken);
    }

    /// <inheritdoc />
    public async Task SendPasswordResetEmailAsync(string email, string token, CancellationToken cancellationToken = default)
    {
        var resetUrl = $"{_settings.BaseUrl}/reset-password?email={Uri.EscapeDataString(email)}&token={Uri.EscapeDataString(token)}";
        
        var htmlBody = $@"
<!DOCTYPE html>
<html>
<head>
    <meta charset=""utf-8"">
    <title>Password Reset</title>
    <style>
        body {{ font-family: Arial, sans-serif; line-height: 1.6; color: #333; }}
        .container {{ max-width: 600px; margin: 0 auto; padding: 20px; }}
        .header {{ background: #ff6b6b; color: white; padding: 20px; text-align: center; }}
        .content {{ padding: 30px; background: #f9f9f9; }}
        .button {{ display: inline-block; padding: 12px 30px; background: #ff6b6b; color: white; text-decoration: none; border-radius: 5px; margin: 20px 0; }}
        .footer {{ padding: 20px; text-align: center; font-size: 12px; color: #666; }}
    </style>
</head>
<body>
    <div class=""container"">
        <div class=""header"">
            <h1>Password Reset</h1>
        </div>
        <div class=""content"">
            <p>Hello,</p>
            <p>We received a request to reset your password. Click the button below to proceed:</p>
            <p style=""text-align: center;"">
                <a href=""{resetUrl}"" class=""button"">Reset Password</a>
            </p>
            <p>Or copy and paste this link into your browser:</p>
            <p style=""word-break: break-all; font-size: 12px;"">{resetUrl}</p>
            <p>This link will expire in 1 hour.</p>
            <p>If you did not request a password reset, please ignore this email.</p>
        </div>
        <div class=""footer"">
            <p>&copy; {DateTime.UtcNow.Year} IAM Service. All rights reserved.</p>
        </div>
    </div>
</body>
</html>";

        await SendEmailAsync(email, "Reset Your Password", htmlBody, cancellationToken);
    }
}
