using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Baya.Web.Plugins.Grpc.Services;

namespace Baya.Web.Plugins.Grpc;

/// <summary>
/// gRPC plugin wiring. The plugin exposes the User service over HTTP/2; the client is HTTP/JSON only, so this is
/// an internal/optional surface. <b>gRPC reflection is enabled only in Development</b> (refinement-phase-9 §9.5) —
/// reflection advertises the full service schema and must not be reachable in deployed environments. The endpoint
/// shares the mixed-protocol Kestrel listener (refinement-phase-5 set <c>Http1AndHttp2</c>), so ALPN negotiates
/// HTTP/2 for gRPC clients while the REST API keeps HTTP/1.1 — no dedicated port is required.
/// </summary>
public static class GrpcPluginStartup
{
    public static IServiceCollection ConfigureGrpcPluginServices(this IServiceCollection services, IHostEnvironment environment)
    {
        services.AddGrpc();

        if (environment.IsDevelopment())
            services.AddGrpcReflection();

        return services;
    }

    public static void ConfigureGrpcPipeline(this WebApplication app)
    {
        app.MapGrpcService<UserGrpcServices>();

        if (app.Environment.IsDevelopment())
            app.MapGrpcReflectionService();

        app.MapGet("/GrpcUser", async context =>
        {
            await context.Response.WriteAsync(
                "Communication with this gRPC endpoint must be made through a gRPC client.");
        });
    }
}
