using MediatR;
using WhatsAppService.Domain.AggregatesModel.AutomationFlowAggregate;
using WhatsAppService.Domain.Events;

namespace WhatsAppService.API.BackgroundJobs;

/// <summary>
/// EN: Domain event handler for processing automation triggers on new messages.
/// VI: Domain event handler để xử lý automation triggers khi có tin nhắn mới.
/// </summary>
public class AutomationTriggerHandler : INotificationHandler<MessageReceivedEvent>
{
    private readonly IServiceProvider _serviceProvider;
    private readonly ILogger<AutomationTriggerHandler> _logger;

    public AutomationTriggerHandler(
        IServiceProvider serviceProvider,
        ILogger<AutomationTriggerHandler> logger)
    {
        _serviceProvider = serviceProvider;
        _logger = logger;
    }

    public async Task Handle(MessageReceivedEvent notification, CancellationToken cancellationToken)
    {
        try
        {
            using var scope = _serviceProvider.CreateScope();
            var flowRepository = scope.ServiceProvider.GetRequiredService<IAutomationFlowRepository>();

            // Get active keyword-triggered flows for this shop
            var flows = await flowRepository.GetByTriggerTypeAsync(
                notification.ShopId, 
                TriggerType.Keyword, 
                cancellationToken);

            if (flows.Count == 0)
            {
                return;
            }

            var messageText = notification.Content.Text?.ToLowerInvariant() ?? "";

            foreach (var flow in flows.OrderByDescending(f => f.Priority))
            {
                // TODO: Parse trigger config and check for keyword matches
                // This is a placeholder - actual implementation would parse TriggerConfig JSON
                _logger.LogDebug(
                    "Checking flow {FlowId} for keyword triggers on message from {CustomerWaId}",
                    flow.Id, notification.CustomerWaId);

                // If matched, execute flow steps
                // await ExecuteFlowAsync(flow, notification, cancellationToken);
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error processing automation triggers for message {MessageId}", notification.MessageId);
        }
    }
}
