using Microsoft.EntityFrameworkCore;
using SimpleLIS.Models;

namespace SimpleLIS.Services;

public class PatientService
{
    private readonly HL7DbContext _context;

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


    public async Task<Patient> CreatePatientAsync(Patient patient)
    {
        _context.Patients.Add(patient);
        await _context.SaveChangesAsync();
        return patient;
    }

    public async Task<Patient> GetPatientByIdAsync(int id)
    {
#pragma warning disable CS8603
        return await _context.Patients.FirstOrDefaultAsync(p => p.PatientId == id);
#pragma warning restore CS8603
    }

    public async Task<IEnumerable<Patient>> ListPatientsAsync()
    {
        return await _context.Patients.ToListAsync();
    }

    public async Task<Patient> UpdatePatientAsync(Patient patient)
    {
        _context.Patients.Update(patient);
        await _context.SaveChangesAsync();
        return patient;
    }

    public async Task<bool> DeletePatientAsync(int id)
    {
        var patient = await GetPatientByIdAsync(id);
        if (patient == null) return false;

        _context.Patients.Remove(patient);
        await _context.SaveChangesAsync();
        return true;
    }

    public async Task<bool> PatientExistsAsync(int id)
    {
        return await _context.Patients.AnyAsync(p => p.PatientId == id);
    }
}
