using Microsoft.EntityFrameworkCore;
using MktXService.Domain.AggregatesModel.AIConversationSessionAggregate;
using MktXService.Domain.SeedWork;

namespace MktXService.Infrastructure.Repositories;

/// <summary>
/// EN: Repository implementation for AIConversationSession aggregate.
/// VI: Triển khai repository cho AIConversationSession aggregate.
/// </summary>
public class AIConversationSessionRepository : IAIConversationSessionRepository
{
    private readonly MktXServiceContext _context;

    public IUnitOfWork UnitOfWork => _context;

    public AIConversationSessionRepository(MktXServiceContext context)
    {
        _context = context ?? throw new ArgumentNullException(nameof(context));
    }

    public AIConversationSession Add(AIConversationSession session)
    {
        return _context.AIConversationSessions.Add(session).Entity;
    }

    public void Update(AIConversationSession session)
    {
        _context.Entry(session).State = EntityState.Modified;
    }

    public async Task<AIConversationSession?> GetByIdAsync(Guid id)
    {
        return await _context.AIConversationSessions.FirstOrDefaultAsync(s => s.Id == id);
    }

    public async Task<AIConversationSession?> GetByConversationIdAsync(Guid conversationId)
    {
        return await _context.AIConversationSessions
            .FirstOrDefaultAsync(s => EF.Property<Guid>(s, "_conversationId") == conversationId);
    }

    public async Task<AIConversationSession?> GetActiveByConversationIdAsync(Guid conversationId)
    {
        return await _context.AIConversationSessions
            .FirstOrDefaultAsync(s => 
                EF.Property<Guid>(s, "_conversationId") == conversationId &&
                EF.Property<bool>(s, "_isActive") == true);
    }
}
