using MediatR;
using MktZaloService.Domain.AggregatesModel.ChatbotRuleAggregate;
using MktZaloService.API.Application.Commands.Rules;

namespace MktZaloService.API.Application.Queries.Rules;

/// <summary>
/// EN: Query to get all chatbot rules.
/// VI: Query để lấy tất cả quy tắc chatbot.
/// </summary>
public record GetChatbotRulesQuery(bool IncludeInactive = false) : IRequest<List<ChatbotRuleDto>>;

/// <summary>
/// EN: DTO for chatbot rule.
/// VI: DTO cho quy tắc chatbot.
/// </summary>
public record ChatbotRuleDto(
    Guid Id,
    string Name,
    string? Description,
    string Type,
    int Priority,
    bool IsActive,
    string ActionType,
    string? ResponseText,
    Guid? TemplateId,
    List<RuleConditionDto> Conditions,
    int MatchCount,
    DateTime? LastMatchedAt,
    DateTime CreatedAt
);

/// <summary>
/// EN: Handler for GetChatbotRulesQuery.
/// VI: Handler cho GetChatbotRulesQuery.
/// </summary>
public class GetChatbotRulesQueryHandler : IRequestHandler<GetChatbotRulesQuery, List<ChatbotRuleDto>>
{
    private readonly IChatbotRuleRepository _ruleRepository;

    public GetChatbotRulesQueryHandler(IChatbotRuleRepository ruleRepository)
    {
        _ruleRepository = ruleRepository;
    }

    public async Task<List<ChatbotRuleDto>> Handle(
        GetChatbotRulesQuery request,
        CancellationToken cancellationToken)
    {
        var rules = request.IncludeInactive
            ? await _ruleRepository.GetAllAsync(cancellationToken)
            : await _ruleRepository.GetActiveRulesOrderedByPriorityAsync(cancellationToken);

        return rules.Select(r => new ChatbotRuleDto(
            r.Id,
            r.Name,
            r.Description,
            r.Type.ToString(),
            r.Priority,
            r.IsActive,
            r.Action.ActionType.ToString(),
            r.Action.ResponseText,
            r.Action.TemplateId,
            r.Conditions.Select(c => new RuleConditionDto(c.Field, c.Operator, c.Value)).ToList(),
            r.MatchCount,
            r.LastMatchedAt,
            r.CreatedAt
        )).ToList();
    }
}
