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

namespace QuantEngine.Web.Pages.Admin.Collection;

[Authorize(AuthenticationSchemes = AdminAuthDefaults.Scheme)]
public class DetailModel : PageModel
{
    private readonly ICollectionReadRepository _collectionRepository;
    private readonly ILogger<DetailModel> _logger;

    public CollectionRunRecord? Run { get; set; }

    public DetailModel(ICollectionReadRepository collectionRepository, ILogger<DetailModel> logger)
    {
        _collectionRepository = collectionRepository;
        _logger = logger;
    }

    public async Task OnGetAsync([FromQuery] string? runId, [FromRoute] string? routeRunId)
    {
        var targetRunId = runId ?? routeRunId;
        if (string.IsNullOrEmpty(targetRunId))
        {
            if (RouteData.Values.TryGetValue("runId", out var routeVal))
            {
                targetRunId = routeVal?.ToString();
            }
        }

        if (string.IsNullOrEmpty(targetRunId))
        {
            _logger.LogWarning("Detail page loaded without a runId");
            return;
        }

        try
        {
            var runs = await _collectionRepository.GetRecentRunsAsync(limit: 100);
            Run = runs.FirstOrDefault(r => r.RunId == targetRunId);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to load collection run detail for runId: {RunId}", targetRunId);
        }
    }
}
