using Microsoft.EntityFrameworkCore;
using MktZaloService.Domain.AggregatesModel.ChatbotRuleAggregate;
using MktZaloService.Domain.SeedWork;

namespace MktZaloService.Infrastructure.Repositories;

/// <summary>
/// EN: Repository implementation for ChatbotRule aggregate.
/// VI: Repository implementation cho ChatbotRule aggregate.
/// </summary>
public class ChatbotRuleRepository : IChatbotRuleRepository
{
    private readonly MktZaloServiceContext _context;

    public IUnitOfWork UnitOfWork => _context;

    public ChatbotRuleRepository(MktZaloServiceContext context)
    {
        _context = context ?? throw new ArgumentNullException(nameof(context));
    }

    /// <summary>
    /// EN: Get rule by ID.
    /// VI: Lấy quy tắc theo ID.
    /// </summary>
    public async Task<ChatbotRule?> GetByIdAsync(Guid id, CancellationToken ct = default)
    {
        return await _context.ChatbotRules
            .Include(r => r.Conditions)
            .FirstOrDefaultAsync(r => r.Id == id, ct);
    }

    /// <summary>
    /// EN: Get all active rules ordered by priority (descending).
    /// VI: Lấy tất cả quy tắc đang hoạt động theo thứ tự ưu tiên (giảm dần).
    /// </summary>
    public async Task<List<ChatbotRule>> GetActiveRulesOrderedByPriorityAsync(CancellationToken ct = default)
    {
        return await _context.ChatbotRules
            .Where(r => r.IsActive)
            .Include(r => r.Conditions)
            .OrderByDescending(r => r.Priority)
            .ThenBy(r => r.Name)
            .ToListAsync(ct);
    }

    /// <summary>
    /// EN: Get all rules (including inactive).
    /// VI: Lấy tất cả quy tắc (bao gồm không hoạt động).
    /// </summary>
    public async Task<List<ChatbotRule>> GetAllAsync(CancellationToken ct = default)
    {
        return await _context.ChatbotRules
            .Include(r => r.Conditions)
            .OrderByDescending(r => r.Priority)
            .ThenBy(r => r.Name)
            .ToListAsync(ct);
    }

    /// <summary>
    /// EN: Add a new rule.
    /// VI: Thêm quy tắc mới.
    /// </summary>
    public ChatbotRule Add(ChatbotRule rule)
    {
        return _context.ChatbotRules.Add(rule).Entity;
    }

    /// <summary>
    /// EN: Update an existing rule.
    /// VI: Cập nhật quy tắc hiện có.
    /// </summary>
    public void Update(ChatbotRule rule)
    {
        _context.Entry(rule).State = EntityState.Modified;
    }

    /// <summary>
    /// EN: Delete a rule.
    /// VI: Xóa một quy tắc.
    /// </summary>
    public void Delete(ChatbotRule rule)
    {
        _context.ChatbotRules.Remove(rule);
    }
}
