using Eis.Application.Public;

namespace Eis.Web.Public;

public static class PublicEndpoints
{
    public static IEndpointRouteBuilder MapNativePublicEndpoints(this IEndpointRouteBuilder endpoints)
    {
        endpoints.MapGet("/api/public/home", async (
            HttpContext context,
            IPublicQueryService queries,
            CancellationToken cancellationToken) =>
        {
            context.Response.Headers["X-EIS-Implementation"] = "aspnet-core";
            return Results.Json(await queries.GetHomeAsync(cancellationToken));
        });

        endpoints.MapGet("/api/public/notices/{id}", async (
            string id,
            HttpContext context,
            IPublicQueryService queries,
            CancellationToken cancellationToken) =>
        {
            context.Response.Headers["X-EIS-Implementation"] = "aspnet-core";
            var notice = await queries.GetNoticeAsync(id, cancellationToken);
            return notice is null
                ? Results.Json(new { ok = false, message = "通知不存在或尚未发布" }, statusCode: StatusCodes.Status404NotFound)
                : Results.Json(new { ok = true, notice });
        });

        endpoints.MapGet("/api/public/announcements", async (
            HttpContext context,
            IPublicQueryService queries,
            CancellationToken cancellationToken) =>
        {
            context.Response.Headers["X-EIS-Implementation"] = "aspnet-core";
            return Results.Json(await queries.GetAnnouncementsAsync(cancellationToken));
        });

        endpoints.MapGet("/api/public/verifications/{code}", async (
            string code,
            HttpContext context,
            IPublicQueryService queries,
            CancellationToken cancellationToken) =>
        {
            context.Response.Headers["X-EIS-Implementation"] = "aspnet-core";
            var verification = await queries.VerifyDocumentAsync(code, cancellationToken);
            return verification is null
                ? Results.Json(new { ok = false, message = "未查询到有效文书，请核对防伪码" }, statusCode: StatusCodes.Status404NotFound)
                : Results.Json(verification);
        });

        return endpoints;
    }
}
