using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Infrastructure.Configuration;
using Kavenegar;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace CMSMicroservice.Infrastructure.Services;

/// <summary>
/// پیاده‌سازی سرویس ارسال SMS با کاوه‌نگار
/// </summary>
public class KavenegarService : IKavenegarService
{
    private readonly KavenegarApi? _kavenegarApi;
    private readonly SmsSettings _smsSettings;
    private readonly ILogger<KavenegarService> _logger;

    public KavenegarService(
        IOptions<SmsSettings> smsSettings,
        ILogger<KavenegarService> logger)
    {
        _smsSettings = smsSettings.Value;
        _logger = logger;
        
        // Initialize Kavenegar API
        if (_smsSettings.Enabled && !string.IsNullOrEmpty(_smsSettings.KavenegarApiKey))
        {
            try
            {
                _kavenegarApi = new KavenegarApi(_smsSettings.KavenegarApiKey);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "❌ Failed to initialize Kavenegar API");
            }
        }
    }

    /// <inheritdoc />
    public async Task SendAsync(string mobile, string message)
    {
        if (!_smsSettings.Enabled)
        {
            _logger.LogInformation("SMS is disabled. Skipping send to {Mobile}", mobile);
            return;
        }

        if (_kavenegarApi == null)
        {
            _logger.LogWarning("⚠️ Kavenegar API not initialized, cannot send SMS");
            return;
        }

        try
        {
            // Kavenegar Send is synchronous
            await Task.Run(() =>
            {
                var result = _kavenegarApi.Send(
                    sender: _smsSettings.Sender, 
                    receptor: mobile, 
                    message: message);

                _logger.LogInformation("📱 SMS sent successfully to {Mobile}, MessageId: {MessageId}", mobile, result.Messageid);
            });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "❌ Kavenegar error sending SMS to {Mobile}: {Message}", mobile, ex.Message);
            throw;
        }
    }

    /// <inheritdoc />
    public async Task VerifyLookupAsync(string mobile, string token, string template = "OTP")
    {
        if (!_smsSettings.Enabled)
        {
            _logger.LogInformation("SMS is disabled. Skipping VerifyLookup to {Mobile}", mobile);
            return;
        }

        if (_kavenegarApi == null)
        {
            _logger.LogWarning("⚠️ Kavenegar API not initialized, cannot send VerifyLookup");
            return;
        }

        try
        {
            // Kavenegar VerifyLookup is synchronous
            await Task.Run(() =>
            {
                var result = _kavenegarApi.VerifyLookup(
                    receptor: mobile, 
                    token: token, 
                    template: template);

                _logger.LogInformation("📱 VerifyLookup SMS sent successfully to {Mobile} with template {Template}, MessageId: {MessageId}", 
                    mobile, template, result.Messageid);
            });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "❌ Kavenegar error sending VerifyLookup to {Mobile}: {Message}", mobile, ex.Message);
            throw;
        }
    }

    /// <inheritdoc />
    public async Task VerifyLookupAsync(string mobile, string token, string token2, string template)
    {
        if (!_smsSettings.Enabled)
        {
            _logger.LogInformation("SMS is disabled. Skipping VerifyLookup to {Mobile}", mobile);
            return;
        }

        if (_kavenegarApi == null)
        {
            _logger.LogWarning("⚠️ Kavenegar API not initialized, cannot send VerifyLookup");
            return;
        }

        try
        {
            await Task.Run(() =>
            {
                var result = _kavenegarApi.VerifyLookup(
                    receptor: mobile,
                    token: token,
                    token2: token2,
                    token3: "",
                    template: template);

                _logger.LogInformation("📱 VerifyLookup SMS sent to {Mobile} with template {Template} (token2), MessageId: {MessageId}",
                    mobile, template, result.Messageid);
            });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "❌ Kavenegar error sending VerifyLookup to {Mobile}: {Message}", mobile, ex.Message);
            throw;
        }
    }
}
