import type { Hono } from "hono";
import { z } from "zod";
import * as templateManager from "../template-manager.js";
import { parseBody } from "../validation.js";
import { notFound, AppError } from "../errors.js";

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

const templateConfigSchema = z.object({
  backend: z.enum(["claude", "codex"]).default("claude"),
  model: z.string().max(200).optional(),
  permissionMode: z.string().max(100).optional(),
  cwd: z.string().max(1000).optional(),
  envSlug: z.string().max(200).optional(),
  codexInternetAccess: z.boolean().optional(),
});

const templateCreateSchema = z.object({
  name: z.string().max(200),
  description: z.string().max(1000).optional().default(""),
  config: templateConfigSchema,
});

const templateUpdateSchema = z.object({
  name: z.string().max(200).optional(),
  description: z.string().max(1000).optional(),
  config: templateConfigSchema.optional(),
});

export function registerTemplateRoutes(api: Hono): void {
  api.get("/templates", (c) => {
    try {
      return c.json(templateManager.listTemplates());
    } catch (e: unknown) {
      return c.json({ error: e instanceof Error ? e.message : String(e) }, 500);
    }
  });

  api.get("/templates/:id", (c) => {
    const template = templateManager.getTemplate(c.req.param("id"));
    if (!template) throw notFound("Template not found");
    return c.json(template);
  });

  api.post("/templates", async (c) => {
    const parsed = await parseBody(c, templateCreateSchema);
    if (!parsed.success) return parsed.response;
    const body = parsed.data;
    try {
      const template = templateManager.createTemplate(
        body.name,
        body.description,
        body.config,
      );
      return c.json(template, 201);
    } catch (e: unknown) {
      return c.json({ error: e instanceof Error ? e.message : String(e) }, 400);
    }
  });

  api.put("/templates/:id", async (c) => {
    const parsed = await parseBody(c, templateUpdateSchema);
    if (!parsed.success) return parsed.response;
    const body = parsed.data;
    try {
      const template = templateManager.updateTemplate(c.req.param("id"), body);
      if (!template) throw notFound("Template not found");
      return c.json(template);
    } catch (e: unknown) {
      if (e instanceof AppError) throw e;
      return c.json({ error: e instanceof Error ? e.message : String(e) }, 400);
    }
  });

  api.delete("/templates/:id", (c) => {
    const deleted = templateManager.deleteTemplate(c.req.param("id"));
    if (!deleted) throw notFound("Template not found");
    return c.json({ ok: true });
  });
}
