using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using EonaCat.LogStack.Status.Data;
using EonaCat.LogStack.Status.Models;
using Monitor = EonaCat.LogStack.Status.Models.Monitor;

namespace EonaCat.LogStack.Status.Pages;

public class MonitorsModel : PageModel
{
    private readonly DatabaseContext _db;
    public MonitorsModel(DatabaseContext db) => _db = db;
    public List<Monitor> Monitors { get; set; } = new();
    public bool IsAdmin { get; set; }
    public Dictionary<int, double> UptimePercent { get; set; } = new();

    public async Task OnGetAsync()
    {
        IsAdmin = HttpContext.Session.GetString("IsAdmin") == "true";
        var q = _db.Monitors.Where(m => m.IsActive);
        if (!IsAdmin)
        {
            q = q.Where(m => m.IsPublic);
        }

        Monitors = await q.OrderBy(m => m.GroupName).ThenBy(m => m.Name).ToListAsync();

        var ids = Monitors.Select(m => m.Id).ToList();
        var cutoff = DateTime.UtcNow.AddDays(-30);
        var checks = await _db.MonitorChecks.Where(c => ids.Contains(c.MonitorId) && c.CheckedAt >= cutoff).ToListAsync();
        foreach (var m in Monitors)
        {
            var mc = checks.Where(c => c.MonitorId == m.Id).ToList();
            UptimePercent[m.Id] = mc.Any() ? (double)mc.Count(c => c.Status == MonitorStatus.Up) / mc.Count * 100 : 0;
        }
    }
}
