using Microsoft.Extensions.Options;
using TrackQrApi.Features.Email.Templates;

namespace TrackQrApi.Features.Email.Services;

/// <summary>
///     Development email service that logs emails to console instead of sending them.
///     Useful for testing without a real SMTP server.
/// </summary>
public class ConsoleEmailService(
    IOptions<EmailSettings> settings,
    ILogger<ConsoleEmailService> logger)
    : IEmailService
{
    private readonly EmailSettings _settings = settings.Value;

    public Task SendPasswordResetEmailAsync(string toEmail, string resetToken, CancellationToken ct = default)
    {
        var resetUrl = $"{_settings.BaseUrl}/reset-password?token={Uri.EscapeDataString(resetToken)}";
        var (subject, _, textBody) = EmailTemplates.PasswordReset(resetUrl);

        LogEmail(toEmail, subject, textBody, resetUrl);
        return Task.CompletedTask;
    }

    public Task SendEmailVerificationAsync(string toEmail, string verificationToken, CancellationToken ct = default)
    {
        var verifyUrl = $"{_settings.BaseUrl}/verify-email?token={Uri.EscapeDataString(verificationToken)}";
        var (subject, _, textBody) = EmailTemplates.EmailVerification(verifyUrl);

        LogEmail(toEmail, subject, textBody, verifyUrl);
        return Task.CompletedTask;
    }

    public Task SendWelcomeEmailAsync(string toEmail, string userName, CancellationToken ct = default)
    {
        var dashboardUrl = $"{_settings.BaseUrl}/dashboard";
        var (subject, _, textBody) = EmailTemplates.Welcome(userName, dashboardUrl);

        LogEmail(toEmail, subject, textBody, dashboardUrl);
        return Task.CompletedTask;
    }

    private void LogEmail(string toEmail, string subject, string body, string actionUrl)
    {
        logger.LogInformation($"""

                               ╔══════════════════════════════════════════════════════════════╗
                               ║                    EMAIL (Console Mode)                      ║
                               ╚══════════════════════════════════════════════════════════════╝
                                To: {toEmail}
                                Subject: {subject}
                                Action URL: {actionUrl}
                                
                               """);
    }
}