import type { FastifyInstance } from "fastify";
import { z } from "zod";
import { createDocsRepository } from "./repository.js";

const searchQuery = z.object({
  q: z.string().trim().default(""),
  limit: z.coerce.number().int().min(1).max(20).default(5),
});

const listQuery = z.object({
  limit: z.coerce.number().int().min(1).max(1000).default(500),
});

export const registerDocsRoutes = async (app: FastifyInstance) => {
  const docs = createDocsRepository();

  app.get("/api/docs", async (request) => {
    const query = listQuery.parse(request.query);
    // Await explicitly so Fastify serializes a real array, not an
    // unresolved Promise which would be `{}` in the response body.
    const [items, total] = await Promise.all([docs.list(query.limit), docs.count()]);
    return { items, total };
  });

  app.get("/api/docs/search", async (request) => {
    const query = searchQuery.parse(request.query);
    const items = await docs.search(query.q, query.limit);
    return { items };
  });

  app.get("/api/docs/:id", async (request, reply) => {
    const params = z.object({ id: z.string().min(1) }).parse(request.params);
    const doc = docs.get(params.id);

    if (!doc) {
      return reply.code(404).send({ error: "doc_not_found" });
    }

    return doc;
  });
};
