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)
    {
        return await _context.Patients
            .Include(p => p.Messages)
            .FirstOrDefaultAsync(p => p.PatientId == id);
    }

    public async Task<List<Observation>> GetPatientObservationById(int id){
        return await _context.Observations.Include(observation=>observation.Message)
        .Where(observation=>observation.Message.PatientId==id).ToListAsync();
    }

    public async Task<List<Observation>> GetPatientObservationByHL7PatientId(string id){
        return await _context.Observations.Include(observation => observation.Message)
        .Where(observation => observation.Message.Patient.HL7PatientId == id).ToListAsync();
    }

    public async Task<IEnumerable<Patient>> ListPatientsAsync()
    {
        return await _context.Patients
            .Include(p => p.Messages)
            .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);
    }
    public async Task<Patient?> GetPatientByNameAndDOB(string firstName, string lastName, DateTime dateOfBirth)
    {
        return await _context.Patients
            .FirstOrDefaultAsync(p => 
                p.FirstName == firstName && 
                p.LastName == lastName && 
                p.DateOfBirth == dateOfBirth);
    }


}
