using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using FastEndpoints;
using QuantEngine.Application.Interfaces;

namespace QuantEngine.Web.Endpoints;

public record ApiGridRunDto(
    string RunId,
    string StartedAt,
    string? FinishedAt,
    string Status,
    int TotalSnapshots,
    int TotalErrors
);

public record ApiGridDataResponse(
    bool IsConnected,
    int TotalCount,
    List<ApiGridRunDto> Items
);

/// <summary>
/// FastEndpoints API for High-Density Vue 3 / AG Grid Dashboard Data
/// SOLID: Single Responsibility for serving clean DTO read-models to AG Grid.
/// </summary>
public class GetGridDataEndpoint : EndpointWithoutRequest<ApiGridDataResponse>
{
    private readonly ICollectionReadModelService _readModelService;

    public GetGridDataEndpoint(ICollectionReadModelService readModelService)
    {
        _readModelService = readModelService;
    }

    public override void Configure()
    {
        Get("/api/admin/grid-data");
        AllowAnonymous(); // Accessible by Vue 3 Frontend
    }

    public override async Task HandleAsync(CancellationToken ct)
    {
        var runs = await _readModelService.GetRecentRunsAsync(100);
        var items = new List<ApiGridRunDto>();

        foreach (var run in runs)
        {
            items.Add(new ApiGridRunDto(
                run.RunId,
                run.StartedAt,
                run.FinishedAt,
                run.Status,
                run.TotalSnapshots ?? 0,
                run.TotalErrors ?? 0
            ));
        }

        await SendAsync(new ApiGridDataResponse(
            IsConnected: true,
            TotalCount: items.Count,
            Items: items
        ), cancellation: ct);
    }
}
