using Microsoft.EntityFrameworkCore;
using MktZaloService.Domain.AggregatesModel.TemplateAggregate;
using MktZaloService.Domain.Enums;
using MktZaloService.Domain.SeedWork;

namespace MktZaloService.Infrastructure.Repositories;

/// <summary>
/// EN: Repository implementation for MessageTemplate aggregate.
/// VI: Repository implementation cho MessageTemplate aggregate.
/// </summary>
public class MessageTemplateRepository : IMessageTemplateRepository
{
    private readonly MktZaloServiceContext _context;

    public IUnitOfWork UnitOfWork => _context;

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

    /// <summary>
    /// EN: Get template by ID.
    /// VI: Lấy mẫu theo ID.
    /// </summary>
    public async Task<MessageTemplate?> GetByIdAsync(Guid id, CancellationToken ct = default)
    {
        return await _context.MessageTemplates
            .Include(t => t.Parameters)
            .FirstOrDefaultAsync(t => t.Id == id, ct);
    }

    /// <summary>
    /// EN: Find template by Zalo template ID.
    /// VI: Tìm mẫu theo Zalo template ID.
    /// </summary>
    public async Task<MessageTemplate?> FindByZaloTemplateIdAsync(
        string zaloTemplateId,
        CancellationToken ct = default)
    {
        return await _context.MessageTemplates
            .Include(t => t.Parameters)
            .FirstOrDefaultAsync(t => t.ZaloTemplateId == zaloTemplateId, ct);
    }

    /// <summary>
    /// EN: Get all approved templates.
    /// VI: Lấy tất cả mẫu đã được phê duyệt.
    /// </summary>
    public async Task<List<MessageTemplate>> GetApprovedTemplatesAsync(CancellationToken ct = default)
    {
        return await _context.MessageTemplates
            .Where(t => t.Status == TemplateStatus.Approved)
            .Include(t => t.Parameters)
            .OrderBy(t => t.Name)
            .ToListAsync(ct);
    }

    /// <summary>
    /// EN: Get all templates.
    /// VI: Lấy tất cả mẫu.
    /// </summary>
    public async Task<List<MessageTemplate>> GetAllAsync(CancellationToken ct = default)
    {
        return await _context.MessageTemplates
            .Include(t => t.Parameters)
            .OrderBy(t => t.Name)
            .ToListAsync(ct);
    }

    /// <summary>
    /// EN: Add a new template.
    /// VI: Thêm mẫu mới.
    /// </summary>
    public MessageTemplate Add(MessageTemplate template)
    {
        return _context.MessageTemplates.Add(template).Entity;
    }

    /// <summary>
    /// EN: Update an existing template.
    /// VI: Cập nhật mẫu hiện có.
    /// </summary>
    public void Update(MessageTemplate template)
    {
        _context.Entry(template).State = EntityState.Modified;
    }
}
