using Microsoft.EntityFrameworkCore;

public class PatientRegistryService : IPatientRegistryService
{
    private readonly AppDbContext _db;

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

    public async Task<IReadOnlyList<PatientSearchResult>> SearchAsync(string query, int limit = 20)
    {
        var trimmed = query.Trim();
        if (trimmed.Length < 2)
            return Array.Empty<PatientSearchResult>();

        var pattern = $"%{trimmed}%";

        return await _db.Patients
            .AsNoTracking()
            .Where(p =>
                EF.Functions.ILike(p.FullName, pattern) ||
                EF.Functions.ILike(p.Mrn, pattern))
            .OrderBy(p => p.FullName)
            .Take(limit)
            .Select(p => new PatientSearchResult(p.Id, p.FullName, p.Mrn))
            .ToListAsync();
    }
}
