import type { Hono } from "hono";
import { z } from "zod";
import * as promptManager from "../prompt-manager.js";
import { parseBody } from "../validation.js";

// ─── Zod Schemas ──────────────────────────────────────────────────

const promptCreateSchema = z.object({
  title: z.string().max(500).optional(),
  name: z.string().max(500).optional(),
  content: z.string().max(200_000).optional().default(""),
  scope: z.enum(["global", "project"]).default("global"),
  cwd: z.string().max(1000).optional(),
});

const promptUpdateSchema = z.object({
  title: z.string().max(500).optional(),
  name: z.string().max(500).optional(),
  content: z.string().max(200_000).optional(),
});

export function registerPromptRoutes(api: Hono): void {
  api.get("/prompts", (c) => {
    try {
      const cwd = c.req.query("cwd");
      const scope = c.req.query("scope");
      const normalizedScope =
        scope === "global" || scope === "project" || scope === "all"
          ? scope
          : undefined;
      return c.json(promptManager.listPrompts({ cwd, scope: normalizedScope }));
    } catch (e: unknown) {
      return c.json({ error: e instanceof Error ? e.message : String(e) }, 500);
    }
  });

  api.get("/prompts/:id", (c) => {
    const prompt = promptManager.getPrompt(c.req.param("id"));
    if (!prompt) return c.json({ error: "Prompt not found" }, 404);
    return c.json(prompt);
  });

  api.post("/prompts", async (c) => {
    const parsed = await parseBody(c, promptCreateSchema);
    if (!parsed.success) return parsed.response;
    const body = parsed.data;
    try {
      const prompt = promptManager.createPrompt(
        String(body.title || body.name || ""),
        body.content,
        body.scope,
        body.cwd,
      );
      return c.json(prompt, 201);
    } catch (e: unknown) {
      return c.json({ error: e instanceof Error ? e.message : String(e) }, 400);
    }
  });

  api.put("/prompts/:id", async (c) => {
    const parsed = await parseBody(c, promptUpdateSchema);
    if (!parsed.success) return parsed.response;
    const body = parsed.data;
    try {
      const prompt = promptManager.updatePrompt(c.req.param("id"), {
        name: body.title ?? body.name,
        content: body.content,
      });
      if (!prompt) return c.json({ error: "Prompt not found" }, 404);
      return c.json(prompt);
    } catch (e: unknown) {
      return c.json({ error: e instanceof Error ? e.message : String(e) }, 400);
    }
  });

  api.delete("/prompts/:id", (c) => {
    const deleted = promptManager.deletePrompt(c.req.param("id"));
    if (!deleted) return c.json({ error: "Prompt not found" }, 404);
    return c.json({ ok: true });
  });
}
