using MediatR;
using FacebookService.Domain.AggregatesModel.ChatbotAggregate;

namespace FacebookService.API.Application.Commands;

/// <summary>
/// EN: Handler for CreateChatbotFlowCommand.
/// VI: Handler cho CreateChatbotFlowCommand.
/// </summary>
public class CreateChatbotFlowCommandHandler : IRequestHandler<CreateChatbotFlowCommand, CreateChatbotFlowCommandResult>
{
    private readonly IChatbotFlowRepository _flowRepository;
    private readonly ILogger<CreateChatbotFlowCommandHandler> _logger;

    public CreateChatbotFlowCommandHandler(
        IChatbotFlowRepository flowRepository,
        ILogger<CreateChatbotFlowCommandHandler> logger)
    {
        _flowRepository = flowRepository ?? throw new ArgumentNullException(nameof(flowRepository));
        _logger = logger ?? throw new ArgumentNullException(nameof(logger));
    }

    public async Task<CreateChatbotFlowCommandResult> Handle(
        CreateChatbotFlowCommand request,
        CancellationToken cancellationToken)
    {
        _logger.LogInformation(
            "Creating chatbot flow: {Name} for shop: {ShopId}",
            request.Name, request.ShopId);

        // EN: Check if trigger value already exists / VI: Kiểm tra trigger value đã tồn tại chưa
        var exists = await _flowRepository.ExistsByTriggerValueAsync(
            request.ShopId, request.TriggerValue, cancellationToken: cancellationToken);

        if (exists)
        {
            _logger.LogWarning(
                "Trigger value already exists: {TriggerValue} for shop: {ShopId}",
                request.TriggerValue, request.ShopId);
            return new CreateChatbotFlowCommandResult(Guid.Empty, Success: false);
        }

        // EN: Parse trigger type / VI: Parse loại trigger
        var triggerType = ParseTriggerType(request.TriggerType);
        if (triggerType is null)
        {
            _logger.LogWarning("Invalid trigger type: {TriggerType}", request.TriggerType);
            return new CreateChatbotFlowCommandResult(Guid.Empty, Success: false);
        }

        // EN: Create flow / VI: Tạo flow
        var flow = new ChatbotFlow(
            request.ShopId,
            request.Name,
            triggerType,
            request.TriggerValue);

        _flowRepository.Add(flow);
        await _flowRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);

        _logger.LogInformation("ChatbotFlow created with ID: {FlowId}", flow.Id);

        return new CreateChatbotFlowCommandResult(flow.Id, Success: true);
    }

    private static FlowTriggerType? ParseTriggerType(string triggerType)
    {
        return triggerType?.ToLowerInvariant() switch
        {
            "getstarted" => FlowTriggerType.GetStarted,
            "keyword" => FlowTriggerType.Keyword,
            "postback" => FlowTriggerType.Postback,
            "fallback" => FlowTriggerType.Fallback,
            _ => null
        };
    }
}
