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

namespace EonaCat.LogStack.Status.Pages;

// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/License for full license details.

public class AnalyticsModel : PageModel
{
    private readonly DatabaseContext _db;
    private readonly MonitoringService _monSvc;

    public AnalyticsModel(DatabaseContext db, MonitoringService monSvc)
    {
        _db = db;
        _monSvc = monSvc;
    }

    public List<UptimeReport> Reports { get; set; } = new();
    /// <summary>Comma-separated response times (ms) for the last 30 checks - keyed by MonitorId.</summary>
    public Dictionary<int, string> SparklineData { get; set; } = new();

    public async Task<IActionResult> OnGetAsync()
    {
        if (HttpContext.Session.GetString("IsAdmin") != "true")
        {
            return RedirectToPage("/Admin/Login");
        }

        var monitors = await _db.Monitors.Where(m => m.IsActive).OrderBy(m => m.Name).ToListAsync();

        foreach (var m in monitors)
        {
            var report = await _monSvc.GetUptimeReportAsync(m.Id);
            Reports.Add(report);

            // Last 30 response times for sparkline
            var recent = await _db.MonitorChecks
                .Where(c => c.MonitorId == m.Id)
                .OrderByDescending(c => c.CheckedAt)
                .Take(30)
                .Select(c => c.ResponseMs)
                .ToListAsync();

            recent.Reverse();
            SparklineData[m.Id] = string.Join(",", recent.Select(v => ((int)v).ToString()));
        }

        return Page();
    }
}
