using System.Net;
using System.Net.Mail;
using System.Text;
using Microsoft.Extensions.Options;

namespace Ikar.Server.Infrastructure.Auth;

public sealed class SmtpEmailCodeSender(IOptions<EmailAuthOptions> options) : IEmailCodeSender
{
    private readonly EmailAuthOptions _options = options.Value;

    public async Task SendLoginCodeAsync(
        string email,
        string code,
        DateTimeOffset expiresAt,
        CancellationToken cancellationToken = default)
    {
        if (!_options.IsConfigured)
        {
            throw new InvalidOperationException("Email login is not configured on the server.");
        }

        using var message = new MailMessage
        {
            From = new MailAddress(_options.FromAddress, _options.FromName),
            Subject = "\u041a\u043e\u0434 \u0432\u0445\u043e\u0434\u0430 \u0432 \u0418\u043a\u0430\u0440",
            SubjectEncoding = Encoding.UTF8,
            Body = $"\u041a\u043e\u0434 \u0432\u0445\u043e\u0434\u0430 \u0432 \u0418\u043a\u0430\u0440: {code}{Environment.NewLine}\u041a\u043e\u0434 \u0434\u0435\u0439\u0441\u0442\u0432\u0443\u0435\u0442 \u0434\u043e {expiresAt:dd.MM.yyyy HH:mm:ss zzz}.",
            BodyEncoding = Encoding.UTF8,
            IsBodyHtml = false
        };
        message.To.Add(new MailAddress(email));

        using var client = new SmtpClient(_options.SmtpHost, _options.SmtpPort)
        {
            EnableSsl = _options.EnableSsl
        };

        if (!string.IsNullOrWhiteSpace(_options.Username))
        {
            client.Credentials = new NetworkCredential(_options.Username, _options.Password);
        }

        await client.SendMailAsync(message, cancellationToken);
    }
}
