using Microsoft.EntityFrameworkCore;

public class SiteService : ISiteService
{
    private readonly AppDbContext _db;

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

    public async Task<ClinicalSite> CreateAsync(CreateSiteRequest req)
    {
        var exists = await _db.ClinicalSites.AnyAsync(s => s.SiteCode == req.SiteCode);
        if (exists)
            throw new ConflictException(
                $"Site code '{req.SiteCode}' is already registered.",
                "SITE_CODE_CONFLICT");

        var site = new ClinicalSite(req.SiteCode, req.Name, req.Address);
        _db.ClinicalSites.Add(site);
        await _db.SaveChangesAsync();
        return site;
    }

    public async Task<ClinicalSite> GetByIdAsync(Guid id)
    {
        var site = await _db.ClinicalSites
            .AsNoTracking()
            .FirstOrDefaultAsync(s => s.Id == id);
        if (site is null)
            throw new NotFoundException("Clinical site not found.", "SITE_NOT_FOUND");
        return site;
    }

    public async Task<List<ClinicalSite>> ListAsync() =>
        await _db.ClinicalSites.AsNoTracking()
            .OrderBy(s => s.SiteCode)
            .ToListAsync();
}