using Microsoft.EntityFrameworkCore;
using SimpleLIS.Models;

namespace SimpleLIS.Services;

public class MessageService
{
    private readonly HL7DbContext _context;

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

    public async Task<Message> CreateMessageAsync(Message message)
    {
        _context.Messages.Add(message);
        await _context.SaveChangesAsync();
        return message;
    }

    public async Task<Message?> GetMessageByIdAsync(int id)
    {
        return await _context.Messages
            .Include(m => m.Observations)
            .FirstOrDefaultAsync(m => m.MessageId == id);
    }

    public async Task<IEnumerable<Message>> ListMessagesAsync()
    {
        return await _context.Messages
            .Include(m => m.Observations)
            .Include(m => m.Patient)
            .ToListAsync();
    }

    public async Task<Message> UpdateMessageAsync(Message message)
    {
        _context.Messages.Update(message);
        await _context.SaveChangesAsync();
        return message;
    }

    public async Task<bool> DeleteMessageAsync(int id)
    {
        var message = await GetMessageByIdAsync(id);
        if (message == null) return false;

        _context.Messages.Remove(message);
        await _context.SaveChangesAsync();
        return true;
    }

    public async Task<bool> MessageExistsAsync(int id)
    {
        return await _context.Messages.AnyAsync(m => m.MessageId == id);
    }
}
