using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Events;
using Microsoft.Extensions.Logging;

namespace CMSMicroservice.Application.OtpTokenCQ.EventHandlers;

public class CreateNewOtpTokenEventHandler : INotificationHandler<CreateNewOtpTokenEvent>
{
    private readonly ILogger<CreateNewOtpTokenEventHandler> _logger;
    private readonly IKavenegarService _kavenegarService;

    public CreateNewOtpTokenEventHandler(
        ILogger<CreateNewOtpTokenEventHandler> logger,
        IKavenegarService kavenegarService)
    {
        _logger = logger;
        _kavenegarService = kavenegarService;
    }

    public async Task Handle(CreateNewOtpTokenEvent notification, CancellationToken cancellationToken)
    {
        _logger.LogInformation("Domain Event: {DomainEvent} for mobile {Mobile}",
            notification.GetType().Name, notification.Item.Mobile);

        try
        {
            var purpose = notification.Item.Purpose?.ToLowerInvariant();

            // برای امضای قرارداد، از الگوی Sign-Contract با GUID به عنوان token2 استفاده شود
            if ((purpose == "signcontract" || purpose == "signclubcontract") 
                && !string.IsNullOrEmpty(notification.SignGuid))
            {
                await _kavenegarService.VerifyLookupAsync(
                    notification.Item.Mobile, notification.PlainCode, notification.SignGuid, "Sign-Contract");
            }
            else
            {
                await _kavenegarService.VerifyLookupAsync(notification.Item.Mobile, notification.PlainCode);
            }

            _logger.LogInformation("OTP SMS sent successfully to {Mobile}", notification.Item.Mobile);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to send OTP SMS to {Mobile}", notification.Item.Mobile);
        }
    }
}
