using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
using ZB.MOM.WW.ScadaBridge.Security;

namespace ZB.MOM.WW.ScadaBridge.CentralUI.ScriptAnalysis;

/// <summary>
/// Minimal-API endpoint group for Roslyn-backed script analysis (diagnostics, completions, hover, etc.).
/// </summary>
public static class ScriptAnalysisEndpoints
{
    /// <summary>Registers all script analysis endpoints under <c>/api/script-analysis</c>.</summary>
    /// <param name="endpoints">The endpoint route builder to register against.</param>
    /// <returns>The same <paramref name="endpoints"/> instance for chaining.</returns>
    public static IEndpointRouteBuilder MapScriptAnalysisEndpoints(this IEndpointRouteBuilder endpoints)
    {
        var group = endpoints.MapGroup("/api/script-analysis")
            .RequireAuthorization(AuthorizationPolicies.RequireDesign);

        group.MapPost("/diagnostics", (DiagnoseRequest req, ScriptAnalysisService svc) =>
            Results.Ok(svc.Diagnose(req)));

        group.MapPost("/completions", async (CompletionsRequest req, ScriptAnalysisService svc) =>
            Results.Ok(await svc.CompleteAsync(req)));

        group.MapPost("/hover", async (HoverRequest req, ScriptAnalysisService svc) =>
            Results.Ok(await svc.Hover(req)));

        group.MapPost("/signature-help", async (SignatureHelpRequest req, ScriptAnalysisService svc) =>
            Results.Ok(await svc.SignatureHelp(req)));

        group.MapPost("/format", (FormatRequest req, ScriptAnalysisService svc) =>
            Results.Ok(svc.Format(req)));

        group.MapPost("/inlay-hints", (InlayHintsRequest req, ScriptAnalysisService svc) =>
            Results.Ok(svc.InlayHints(req)));

        group.MapPost("/run", async (SandboxRunRequest req, ScriptAnalysisService svc, HttpContext http) =>
            Results.Ok(await svc.RunInSandboxAsync(req, http.RequestAborted)));

        return endpoints;
    }
}
