using System.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using SimpleLIS.Models;
using SimpleLIS.Services;

namespace SimpleLIS.Controllers;

public class HomeController : Controller
{
    private readonly ILogger<HomeController> _logger;
    private readonly MessageService _messageService;
    private readonly PatientService _patientService;
    private readonly ObservationService _observationService;

    public HomeController(
        ILogger<HomeController> logger,
        MessageService messageService,
        PatientService patientService,
        ObservationService observationService)
    {
        _logger = logger;
        _messageService = messageService;
        _patientService = patientService;
        _observationService = observationService;
    }

    public async Task<IActionResult> Index()
    {
        var patients = await _patientService.ListPatientsAsync();
        var messages = await _messageService.ListMessagesAsync();
        var observations = await _observationService.ListObservationsAsync();

        ViewBag.TotalPatients = patients.Count();
        ViewBag.TotalMessages = messages.Count();
        ViewBag.TotalObservations = observations.Count();
        ViewBag.RecentMessages = messages.OrderByDescending(m => m.Timestamp).Take(5);

        return View();
    }

    public async Task<IActionResult> Patients()
    {
        var patients = await _patientService.ListPatientsAsync();
        return View(patients);
    }

    public async Task<IActionResult> Messages()
    {
        var messages = await _messageService.ListMessagesAsync();
        return View(messages.OrderByDescending(m => m.Timestamp));
    }

    public async Task<IActionResult> Observations()
    {
        var observations = await _observationService.ListObservationsAsync();
        return View(observations);
    }

    public IActionResult Privacy()
    {
        return View();
    }

    [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
    public IActionResult Error()
    {
        return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
    }
}
