import { Hono } from "hono";
import type { Logger } from "pino";
import type { JiraWebhookPayload } from "@/jira/schemas.js";
import type { IJobQueue, JobPayload } from "@/types/index.js";
import { validateWebhookPayload } from "@/server/middleware/validate.js";

type WebhookEnv = {
  Variables: {
    webhookPayload: JiraWebhookPayload;
  };
};

interface WebhookDeps {
  queue: IJobQueue;
  logger: Logger;
}

export function createWebhookRoutes(deps: WebhookDeps): Hono<WebhookEnv> {
  const app = new Hono<WebhookEnv>();

  app.post("/jira/webhook", validateWebhookPayload, async (c) => {
    const payload = c.get("webhookPayload");
    const { issue } = payload;

    const issueType = issue.fields.issuetype.name;
    const status = issue.fields.status.name;

    if (issueType !== "Bug") {
      deps.logger.debug({ issueKey: issue.key, issueType }, "Skipping non-Bug issue");
      return c.json({ skipped: true, reason: "Not a Bug" });
    }

    if (status !== "To Do") {
      deps.logger.debug({ issueKey: issue.key, status }, "Skipping issue not in To Do status");
      return c.json({ skipped: true, reason: "Not in To Do status" });
    }

    const job: JobPayload = {
      jobKind: "jira",
      issueId: issue.id,
      issueKey: issue.key,
      summary: issue.fields.summary,
      description:
        typeof issue.fields.description === "string"
          ? issue.fields.description
          : JSON.stringify(issue.fields.description ?? ""),
    };

    try {
      await deps.queue.enqueue(job);
    } catch (err) {
      deps.logger.error({ err }, "webhook_enqueue_failed");
      return c.json({ error: "Failed to enqueue job" }, 500);
    }

    return c.json({ accepted: true, issueKey: issue.key }, 202);
  });

  return app;
}
