using Health.Application.Diets;

namespace Health.Infrastructure.Diets;

public sealed class EfDietRepository(AppDbContext db) : IDietRepository
{
    private readonly AppDbContext _db = db;

    public async Task<IReadOnlyList<DietRecord>> ListAsync(Guid userId, DateOnly? recordedAt, MealType? mealType, CancellationToken ct)
    {
        var query = _db.DietRecords.Include(d => d.FoodItems).Where(d => d.UserId == userId);

        if (recordedAt.HasValue)
            query = query.Where(r => r.RecordedAt == recordedAt.Value);

        if (mealType.HasValue)
            query = query.Where(r => r.MealType == mealType.Value);

        return await query.OrderByDescending(r => r.RecordedAt).ToListAsync(ct);
    }

    public Task<DietRecord?> GetOwnedAsync(Guid userId, Guid recordId, CancellationToken ct) =>
        _db.DietRecords.FirstOrDefaultAsync(r => r.Id == recordId && r.UserId == userId, ct);

    public async Task AddAsync(DietRecord record, CancellationToken ct) =>
        await _db.DietRecords.AddAsync(record, ct);

    public void Delete(DietRecord record) =>
        _db.DietRecords.Remove(record);

    public Task SaveChangesAsync(CancellationToken ct) =>
        _db.SaveChangesAsync(ct);
}
