using Microsoft.EntityFrameworkCore;
using WhatsAppService.Domain.AggregatesModel.AIAgentAggregate;
using WhatsAppService.Domain.SeedWork;

namespace WhatsAppService.Infrastructure.Repositories;

/// <summary>
/// EN: Repository implementation for AIAgent aggregate.
/// VI: Triển khai repository cho AIAgent aggregate.
/// </summary>
public class AIAgentRepository : IAIAgentRepository
{
    private readonly WhatsAppServiceContext _context;

    public IUnitOfWork UnitOfWork => _context;

    public AIAgentRepository(WhatsAppServiceContext context)
    {
        _context = context ?? throw new ArgumentNullException(nameof(context));
    }

    public async Task<AIAgent> AddAsync(AIAgent agent, CancellationToken cancellationToken = default)
    {
        var entry = await _context.AIAgents.AddAsync(agent, cancellationToken);
        return entry.Entity;
    }

    public void Update(AIAgent agent)
    {
        _context.Entry(agent).State = EntityState.Modified;
    }

    public async Task<AIAgent?> GetByIdAsync(Guid id, CancellationToken cancellationToken = default)
    {
        return await _context.AIAgents.FirstOrDefaultAsync(a => a.Id == id, cancellationToken);
    }

    public async Task<AIAgent?> GetActiveByShopIdAsync(Guid shopId, CancellationToken cancellationToken = default)
    {
        return await _context.AIAgents
            .FirstOrDefaultAsync(a => 
                EF.Property<Guid>(a, "_shopId") == shopId &&
                EF.Property<bool>(a, "_isActive") == true,
                cancellationToken);
    }

    public async Task<IReadOnlyList<AIAgent>> GetByShopIdAsync(Guid shopId, CancellationToken cancellationToken = default)
    {
        return await _context.AIAgents
            .Where(a => EF.Property<Guid>(a, "_shopId") == shopId)
            .OrderByDescending(a => EF.Property<DateTime>(a, "_createdAt"))
            .ToListAsync(cancellationToken);
    }
}
