using Microsoft.EntityFrameworkCore;
using SimpleLIS.Models;

namespace SimpleLIS.Services;

public class ObservationService
{
    private readonly HL7DbContext _context;

    public ObservationService(HL7DbContext context)
    {
        _context = context;
    }

    public async Task<Observation> CreateObservationAsync(Observation observation)
    {
        _context.Observations.Add(observation);
        await _context.SaveChangesAsync();
        return observation;
    }

    public async Task<Observation?> GetObservationByIdAsync(int id)
    {
        return await _context.Observations
            .Include(o => o.Message)
            .FirstOrDefaultAsync(o => o.ObservationId == id);
    }

    public async Task<IEnumerable<Observation>> ListObservationsAsync()
    {
        return await _context.Observations
            .Include(o => o.Message)
                .ThenInclude(m => m.Patient)
            .ToListAsync();
    }

    public async Task<Observation> UpdateObservationAsync(Observation observation)
    {
        _context.Observations.Update(observation);
        await _context.SaveChangesAsync();
        return observation;
    }

    public async Task<bool> DeleteObservationAsync(int id)
    {
        var observation = await GetObservationByIdAsync(id);
        if (observation == null) return false;

        _context.Observations.Remove(observation);
        await _context.SaveChangesAsync();
        return true;
    }

    public async Task<bool> ObservationExistsAsync(int id)
    {
        return await _context.Observations.AnyAsync(o => o.ObservationId == id);
    }
}
