using EntKube.Provisioning.Domain;
using EntKube.SharedKernel.Contracts;
using Microsoft.AspNetCore.Mvc;

namespace EntKube.Provisioning.Features.GetServices;

/// <summary>
/// Lists all provisioned service instances. Optionally filtered by cluster.
/// </summary>
public static class GetServicesEndpoint
{
    public static void Map(IEndpointRouteBuilder app)
    {
        app.MapGet("/api/services", async (
            [FromQuery] Guid? clusterId,
            [FromServices] IServiceInstanceRepository repository,
            CancellationToken ct) =>
        {
            IReadOnlyList<ServiceInstance> instances = clusterId.HasValue
                ? await repository.GetByClusterIdAsync(clusterId.Value, ct)
                : await repository.GetAllAsync(ct);

            List<ServiceSummary> summaries = instances.Select(s => new ServiceSummary(
                s.Id,
                s.ClusterId,
                s.ServiceType.ToString(),
                s.Name,
                s.Namespace,
                s.CurrentState.ToString(),
                s.DesiredState.ToString())).ToList();

            return Results.Ok(ApiResponse<List<ServiceSummary>>.Ok(summaries));
        });
    }
}

public record ServiceSummary(
    Guid Id,
    Guid ClusterId,
    string ServiceType,
    string Name,
    string Namespace,
    string CurrentState,
    string DesiredState);
