using Microsoft.EntityFrameworkCore;
using MiningService.Domain.AggregatesModel.CircleAggregate;
using MiningService.Domain.SeedWork;

namespace MiningService.Infrastructure.Repositories;

/// <summary>
/// EN: Repository implementation for Circle aggregate.
/// VI: Triển khai repository cho Circle aggregate.
/// </summary>
public class CircleRepository : ICircleRepository
{
    private readonly MiningServiceContext _context;

    public IUnitOfWork UnitOfWork => _context;

    public CircleRepository(MiningServiceContext context)
    {
        _context = context ?? throw new ArgumentNullException(nameof(context));
    }

    public async Task<Circle?> GetByIdAsync(Guid id, CancellationToken cancellationToken = default)
    {
        return await _context.Circles
            .Include(c => c.Members)
            .FirstOrDefaultAsync(c => c.Id == id, cancellationToken);
    }

    public async Task<Circle?> GetByOwnerIdAsync(Guid ownerId, CancellationToken cancellationToken = default)
    {
        return await _context.Circles
            .Include(c => c.Members)
            .FirstOrDefaultAsync(c => c.OwnerId == ownerId, cancellationToken);
    }

    public async Task<Circle?> GetByMemberIdAsync(Guid minerId, CancellationToken cancellationToken = default)
    {
        return await _context.Circles
            .Include(c => c.Members)
            .FirstOrDefaultAsync(c => c.Members.Any(m => m.MinerId == minerId && m.IsActive), cancellationToken);
    }

    public Circle Add(Circle circle)
    {
        return _context.Circles.Add(circle).Entity;
    }

    public void Update(Circle circle)
    {
        _context.Entry(circle).State = EntityState.Modified;
    }
}
