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

namespace MktZaloService.API.Application.Commands.Rules;

/// <summary>
/// EN: Handler for DeleteChatbotRuleCommand.
/// VI: Handler cho DeleteChatbotRuleCommand.
/// </summary>
public class DeleteChatbotRuleCommandHandler :
    IRequestHandler<DeleteChatbotRuleCommand, DeleteChatbotRuleResult>,
    IRequestHandler<ToggleChatbotRuleCommand, ToggleChatbotRuleResult>
{
    private readonly IChatbotRuleRepository _ruleRepository;
    private readonly IChatbotRuleCacheService _cacheService;
    private readonly ILogger<DeleteChatbotRuleCommandHandler> _logger;

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

    public async Task<DeleteChatbotRuleResult> Handle(
        DeleteChatbotRuleCommand request,
        CancellationToken cancellationToken)
    {
        var rule = await _ruleRepository.GetByIdAsync(request.RuleId, cancellationToken);

        if (rule == null)
        {
            return new DeleteChatbotRuleResult(false, Error: "Rule not found");
        }

        try
        {
            _ruleRepository.Delete(rule);
            await _ruleRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);
            await _cacheService.InvalidateRulesCacheAsync(cancellationToken);

            _logger.LogInformation(
                "EN: Deleted chatbot rule {RuleId}. VI: Đã xóa quy tắc chatbot {RuleId}",
                request.RuleId);

            return new DeleteChatbotRuleResult(true);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex,
                "EN: Error deleting chatbot rule. VI: Lỗi xóa quy tắc chatbot");
            return new DeleteChatbotRuleResult(false, Error: ex.Message);
        }
    }

    public async Task<ToggleChatbotRuleResult> Handle(
        ToggleChatbotRuleCommand request,
        CancellationToken cancellationToken)
    {
        var rule = await _ruleRepository.GetByIdAsync(request.RuleId, cancellationToken);

        if (rule == null)
        {
            return new ToggleChatbotRuleResult(false, Error: "Rule not found");
        }

        try
        {
            if (request.Activate)
            {
                rule.Activate();
            }
            else
            {
                rule.Deactivate();
            }

            _ruleRepository.Update(rule);
            await _ruleRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);
            await _cacheService.InvalidateRulesCacheAsync(cancellationToken);

            _logger.LogInformation(
                "EN: Toggled rule {RuleId} to {Status}. VI: Đã chuyển trạng thái rule {RuleId} sang {Status}",
                request.RuleId, request.Activate ? "active" : "inactive");

            return new ToggleChatbotRuleResult(true);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex,
                "EN: Error toggling chatbot rule. VI: Lỗi chuyển trạng thái quy tắc chatbot");
            return new ToggleChatbotRuleResult(false, Error: ex.Message);
        }
    }
}
