using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using RR3CommunityServer.Data;
using static RR3CommunityServer.Data.RR3DbContext;

namespace RR3CommunityServer.Pages;

public class AdminModel : PageModel
{
    private readonly RR3DbContext _context;

    public AdminModel(RR3DbContext context)
    {
        _context = context;
    }

    public int TotalUsers { get; set; }
    public int ActiveSessions { get; set; }
    public int TotalDevices { get; set; }
    public int TotalCatalogItems { get; set; }
    public string Uptime { get; set; } = "0:00:00";
    public string ServerUrl { get; set; } = string.Empty;
    public string Platform { get; set; } = string.Empty;
    public string DotNetVersion { get; set; } = string.Empty;
    
    public List<User> RecentUsers { get; set; } = new();
    public List<Session> RecentSessions { get; set; } = new();

    public async Task OnGetAsync()
    {
        // Get statistics
        TotalUsers = await _context.Users.CountAsync();
        TotalDevices = await _context.Devices.CountAsync();
        TotalCatalogItems = await _context.CatalogItems.CountAsync();
        ActiveSessions = await _context.Sessions
            .Where(s => s.ExpiresAt > DateTime.UtcNow)
            .CountAsync();

        // Get recent activity
        RecentUsers = await _context.Users
            .OrderByDescending(u => u.CreatedAt)
            .Take(5)
            .ToListAsync();

        RecentSessions = await _context.Sessions
            .Where(s => s.ExpiresAt > DateTime.UtcNow)
            .OrderByDescending(s => s.CreatedAt)
            .Take(5)
            .ToListAsync();

        // Server info
        var uptime = DateTime.UtcNow - System.Diagnostics.Process.GetCurrentProcess().StartTime.ToUniversalTime();
        Uptime = $"{uptime.Days}d {uptime.Hours}h {uptime.Minutes}m";
        ServerUrl = $"{Request.Scheme}://{Request.Host}";
        Platform = Environment.OSVersion.Platform.ToString();
        DotNetVersion = Environment.Version.ToString();
    }
}
