using Fengling.AuthService.Data;
using Fengling.AuthService.Models;
using Fengling.Platform.Infrastructure;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using OpenIddict.Abstractions;

namespace Fengling.AuthService.Controllers;

[ApiController]
[Route("api/[controller]")]
[Authorize]
public class StatsController(
    ApplicationDbContext context,
    IOpenIddictApplicationManager applicationManager,
    ILogger<StatsController> logger,
    PlatformDbContext platformDbContext)
    : ControllerBase
{

    [HttpGet("dashboard")]
    public async Task<ActionResult<object>> GetDashboardStats()
    {
        var today = DateTime.UtcNow.Date;
        var tomorrow = today.AddDays(1);

        var userCount = await context.Users.CountAsync(u => !u.IsDeleted);
        var tenantCount = await platformDbContext.Tenants.CountAsync(t => !t.IsDeleted);
        var oauthClientCount = await CountOAuthClientsAsync();
        var todayAccessCount = await context.AccessLogs
            .CountAsync(l => l.CreatedAt >= today && l.CreatedAt < tomorrow);

        return Ok(new
        {
            userCount,
            tenantCount,
            oauthClientCount,
            todayAccessCount,
        });
    }

    private async Task<int> CountOAuthClientsAsync()
    {
        var count = 0;
        var applications = applicationManager.ListAsync();
        await foreach (var _ in applications)
        {
            count++;
        }
        return count;
    }

    [HttpGet("system")]
    public ActionResult<object> GetSystemStats()
    {
        var uptime = TimeSpan.FromMilliseconds(Environment.TickCount64);
        var process = System.Diagnostics.Process.GetCurrentProcess();

        return Ok(new
        {
            uptime = $"{uptime.Days}天 {uptime.Hours}小时 {uptime.Minutes}分钟",
            memoryUsed = process.WorkingSet64 / 1024 / 1024,
            cpuTime = process.TotalProcessorTime,
            machineName = Environment.MachineName,
            osVersion = Environment.OSVersion.ToString(),
            processorCount = Environment.ProcessorCount,
        });
    }
}
