// EN: Repository implementation for Resource aggregate.
// VI: Implementation repository cho aggregate Resource.

using BookingService.Domain.AggregatesModel.ResourceAggregate;
using BookingService.Domain.SeedWork;
using Microsoft.EntityFrameworkCore;

namespace BookingService.Infrastructure.Repositories;

public class ResourceRepository : IResourceRepository
{
    private readonly BookingContext _context;

    public IUnitOfWork UnitOfWork => _context;

    public ResourceRepository(BookingContext context)
    {
        _context = context ?? throw new ArgumentNullException(nameof(context));
    }

    public Resource Add(Resource resource)
    {
        return _context.Resources.Add(resource).Entity;
    }

    public void Update(Resource resource)
    {
        _context.Entry(resource).State = EntityState.Modified;
    }

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

    public async Task<List<Resource>> GetByShopIdAsync(Guid shopId, bool? isActive = null, CancellationToken cancellationToken = default)
    {
        var query = _context.Resources.Where(r => r.ShopId == shopId);
        
        if (isActive.HasValue)
        {
            query = query.Where(r => r.IsActive == isActive.Value);
        }

        return await query.ToListAsync(cancellationToken);
    }
}
