using Microsoft.EntityFrameworkCore;
using FacebookService.Domain.AggregatesModel.ChatbotAggregate;
using FacebookService.Domain.SeedWork;

namespace FacebookService.Infrastructure.Repositories;

/// <summary>
/// EN: Repository implementation for AIChatbotConfig aggregate.
/// VI: Triển khai repository cho AIChatbotConfig aggregate.
/// </summary>
public class AIChatbotConfigRepository : IAIChatbotConfigRepository
{
    private readonly FacebookServiceContext _context;

    public IUnitOfWork UnitOfWork => _context;

    public AIChatbotConfigRepository(FacebookServiceContext context)
    {
        _context = context ?? throw new ArgumentNullException(nameof(context));
    }

    /// <inheritdoc/>
    public async Task<AIChatbotConfig?> GetByIdAsync(Guid id, CancellationToken cancellationToken = default)
    {
        return await _context.AIChatbotConfigs
            .Include(c => c.Provider)
            .FirstOrDefaultAsync(c => c.Id == id, cancellationToken);
    }

    /// <inheritdoc/>
    public async Task<AIChatbotConfig?> GetByShopIdAsync(Guid shopId, CancellationToken cancellationToken = default)
    {
        return await _context.AIChatbotConfigs
            .Include(c => c.Provider)
            .FirstOrDefaultAsync(c => EF.Property<Guid>(c, "_shopId") == shopId, cancellationToken);
    }

    /// <inheritdoc/>
    public async Task<AIChatbotConfig?> GetEnabledByShopIdAsync(Guid shopId, CancellationToken cancellationToken = default)
    {
        return await _context.AIChatbotConfigs
            .Include(c => c.Provider)
            .FirstOrDefaultAsync(c => 
                EF.Property<Guid>(c, "_shopId") == shopId &&
                EF.Property<bool>(c, "_isEnabled") == true, 
                cancellationToken);
    }

    /// <inheritdoc/>
    public async Task<bool> ExistsByShopIdAsync(Guid shopId, CancellationToken cancellationToken = default)
    {
        return await _context.AIChatbotConfigs
            .AnyAsync(c => EF.Property<Guid>(c, "_shopId") == shopId, cancellationToken);
    }

    /// <inheritdoc/>
    public AIChatbotConfig Add(AIChatbotConfig config)
    {
        return _context.AIChatbotConfigs.Add(config).Entity;
    }

    /// <inheritdoc/>
    public void Update(AIChatbotConfig config)
    {
        _context.Entry(config).State = EntityState.Modified;
    }
}
