using MediatR;
using Microsoft.Extensions.Logging;
using MktZaloService.Domain.AggregatesModel.ChatbotRuleAggregate;
using MktZaloService.Domain.Enums;
using MktZaloService.Infrastructure.Caching;

namespace MktZaloService.API.Application.Commands.Rules;

/// <summary>
/// EN: Handler for CreateChatbotRuleCommand.
/// VI: Handler cho CreateChatbotRuleCommand.
/// </summary>
public class CreateChatbotRuleCommandHandler 
    : IRequestHandler<CreateChatbotRuleCommand, CreateChatbotRuleResult>
{
    private readonly IChatbotRuleRepository _ruleRepository;
    private readonly IChatbotRuleCacheService _cacheService;
    private readonly ILogger<CreateChatbotRuleCommandHandler> _logger;

    public CreateChatbotRuleCommandHandler(
        IChatbotRuleRepository ruleRepository,
        IChatbotRuleCacheService cacheService,
        ILogger<CreateChatbotRuleCommandHandler> logger)
    {
        _ruleRepository = ruleRepository;
        _cacheService = cacheService;
        _logger = logger;
    }

    public async Task<CreateChatbotRuleResult> Handle(
        CreateChatbotRuleCommand request,
        CancellationToken cancellationToken)
    {
        try
        {
            // EN: Create action based on type / VI: Tạo action theo loại
            var action = request.ActionType switch
            {
                ActionType.SendText => RuleAction.SendText(request.ResponseText ?? string.Empty),
                ActionType.SendTemplate => RuleAction.SendTemplate(request.TemplateId ?? Guid.Empty),
                ActionType.ForwardToHuman => RuleAction.ForwardToHuman(),
                _ => RuleAction.SendText(request.ResponseText ?? string.Empty)
            };

            // EN: Create rule / VI: Tạo quy tắc
            var rule = new ChatbotRule(
                request.Name,
                request.Type,
                action,
                request.Priority,
                request.Description);

            // EN: Add conditions / VI: Thêm điều kiện
            foreach (var condition in request.Conditions)
            {
                rule.AddCondition(condition.Field, condition.Operator, condition.Value);
            }

            _ruleRepository.Add(rule);
            await _ruleRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);

            // EN: Invalidate cache / VI: Xóa cache
            await _cacheService.InvalidateRulesCacheAsync(cancellationToken);

            _logger.LogInformation(
                "EN: Created chatbot rule '{Name}' with ID {Id}. VI: Đã tạo quy tắc chatbot '{Name}' với ID {Id}",
                rule.Name, rule.Id);

            return new CreateChatbotRuleResult(true, RuleId: rule.Id);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex,
                "EN: Error creating chatbot rule. VI: Lỗi tạo quy tắc chatbot");
            return new CreateChatbotRuleResult(false, Error: ex.Message);
        }
    }
}
