using Microsoft.EntityFrameworkCore;

public class SofaService : ISofaService
{
    private readonly AppDbContext _db;

    public SofaService(AppDbContext db) => _db = db;

    public async Task<SofaScore?> GetCurrentAsync(Guid encounterId)
    {
        return await _db.SofaScores
            .AsNoTracking()
            .Where(s => s.EncounterId == encounterId)
            .OrderByDescending(s => s.CalculatedAt)
            .FirstOrDefaultAsync();
    }

    public async Task<SofaScore?> GetBaselineAsync(Guid encounterId)
    {
        return await _db.SofaScores
            .AsNoTracking()
            .FirstOrDefaultAsync(s => s.EncounterId == encounterId && s.IsBaseline);
    }

    public async Task<CursorPage<SofaScore>> GetHistoryAsync(
        Guid encounterId, int limit, string? cursorToken)
    {
        limit = Math.Clamp(limit, 1, 100);

        var query = _db.SofaScores
            .AsNoTracking()
            .Where(s => s.EncounterId == encounterId);

        var items = await query
            .OrderByDescending(s => s.CalculatedAt)
            .ThenByDescending(s => s.Id)
            .Take(limit + 1)
            .ToListAsync();

        var hasMore = items.Count > limit;
        if (hasMore) items.RemoveAt(limit);

        return new CursorPage<SofaScore>(items, null, hasMore);
    }
}
