using JobsMedical.Web.Data;
using JobsMedical.Web.Models;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;

namespace JobsMedical.Web.Pages.Facilities;

public class IndexModel : PageModel
{
    private readonly AppDbContext _db;
    public IndexModel(AppDbContext db) => _db = db;

    public record FacilityRow(Facility Facility, int OpenShifts);
    public List<FacilityRow> Rows { get; private set; } = new();

    public async Task OnGetAsync()
    {
        var today = DateOnly.FromDateTime(DateTime.UtcNow);
        var facilities = await _db.Facilities.Include(f => f.City).OrderBy(f => f.Name).ToListAsync();
        var counts = await _db.Shifts
            .Where(s => s.Status == ShiftStatus.Open && s.Date >= today)
            .GroupBy(s => s.FacilityId)
            .Select(g => new { g.Key, Count = g.Count() })
            .ToDictionaryAsync(x => x.Key, x => x.Count);

        Rows = facilities
            .Select(f => new FacilityRow(f, counts.GetValueOrDefault(f.Id)))
            .ToList();
    }
}
