import type { Context, Next } from "hono";
import { jiraWebhookSchema } from "@/jira/schemas.js";

export async function validateWebhookPayload(c: Context, next: Next): Promise<Response | void> {
  let body: unknown;
  try {
    body = await c.req.json();
  } catch {
    return c.json({ error: "Invalid JSON body" }, 400);
  }

  const result = jiraWebhookSchema.safeParse(body);

  if (!result.success) {
    return c.json(
      {
        error: "Invalid webhook payload",
        details: result.error.issues.map((i) => ({
          path: i.path.join("."),
          message: i.message,
        })),
      },
      400,
    );
  }

  c.set("webhookPayload" as never, result.data as never);
  await next();
}
