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

namespace RR3CommunityServer.Pages;

public class SettingsModel : PageModel
{
    private readonly RR3DbContext _context;

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

    public string ServerUrl { get; set; } = string.Empty;
    public string Platform { get; set; } = string.Empty;
    public string DotNetVersion { get; set; } = string.Empty;
    public string AspNetVersion { get; set; } = string.Empty;
    public string Uptime { get; set; } = string.Empty;
    public int ProcessId { get; set; }
    public long MemoryUsage { get; set; }
    public DatabaseStats DbStats { get; set; } = new();

    public async Task OnGetAsync()
    {
        ServerUrl = $"{Request.Scheme}://{Request.Host}";
        Platform = Environment.OSVersion.ToString();
        DotNetVersion = Environment.Version.ToString();
        AspNetVersion = typeof(IApplicationBuilder).Assembly.GetName().Version?.ToString() ?? "Unknown";
        
        var process = System.Diagnostics.Process.GetCurrentProcess();
        var uptime = DateTime.UtcNow - process.StartTime.ToUniversalTime();
        Uptime = $"{uptime.Days}d {uptime.Hours}h {uptime.Minutes}m {uptime.Seconds}s";
        ProcessId = process.Id;
        MemoryUsage = process.WorkingSet64 / 1024 / 1024; // Convert to MB

        // Get database stats
        DbStats = new DatabaseStats
        {
            Users = await _context.Users.CountAsync(),
            Devices = await _context.Devices.CountAsync(),
            Sessions = await _context.Sessions.CountAsync(),
            Purchases = await _context.Purchases.CountAsync()
        };
    }

    public async Task<IActionResult> OnPostResetDatabaseAsync()
    {
        // Delete all data
        _context.Purchases.RemoveRange(_context.Purchases);
        _context.Sessions.RemoveRange(_context.Sessions);
        _context.Users.RemoveRange(_context.Users);
        _context.Devices.RemoveRange(_context.Devices);
        _context.CatalogItems.RemoveRange(_context.CatalogItems);

        await _context.SaveChangesAsync();

        // Re-seed catalog
        await _context.Database.EnsureDeletedAsync();
        await _context.Database.EnsureCreatedAsync();

        return RedirectToPage();
    }
}

public class DatabaseStats
{
    public int Users { get; set; }
    public int Devices { get; set; }
    public int Sessions { get; set; }
    public int Purchases { get; set; }
}
