using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.RazorPages;
using QuantEngine.Core.Interfaces;
using QuantEngine.Web.Services;

namespace QuantEngine.Web.Pages.Admin.Dashboard;

[Authorize(AuthenticationSchemes = AdminAuthDefaults.Scheme)]
public class IndexModel : PageModel
{
    private readonly IWorkspaceRepository _workspaceRepository;
    private readonly ICollectionRepository _collectionRepository;
    private readonly ILogger<IndexModel> _logger;

    public int? ActiveUsersCount { get; set; }
    public int? RecentRunsCount { get; set; }

    public IndexModel(IWorkspaceRepository workspaceRepository, ICollectionRepository collectionRepository, ILogger<IndexModel> logger)
    {
        _workspaceRepository = workspaceRepository;
        _collectionRepository = collectionRepository;
        _logger = logger;
    }

    public async Task OnGetAsync()
    {
        try
        {
            var accounts = await _workspaceRepository.GetAccountsAsync();
            ActiveUsersCount = accounts.Count(a => string.Equals(a.IsActive, "true", StringComparison.OrdinalIgnoreCase));

            var dashboard = await _collectionRepository.GetDashboardStateAsync();
            RecentRunsCount = string.IsNullOrEmpty(dashboard?.LastRunId) ? 0 : 1;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Dashboard data loading failed");
        }
    }
}
