import { NextRequest } from "next/server";
import { z } from "zod";
import { entriesByLanguage } from "@/server/repo";

const paramsSchema = z.object({ id: z.string().trim().length(2) });
const querySchema = z.object({
  page: z.coerce.number().int().positive().optional(),
  pageSize: z.coerce.number().int().positive().max(100).optional(),
});

export async function GET(req: NextRequest, ctx: { params: Promise<{ id: string }> }) {
  const raw = await ctx.params;
  const p = paramsSchema.safeParse(raw);
  if (!p.success) {
    return new Response(JSON.stringify({ error: p.error.flatten() }), { status: 400 });
  }
  const { searchParams } = new URL(req.url);
  const q = querySchema.safeParse({
    page: searchParams.get("page") ?? undefined,
    pageSize: searchParams.get("pageSize") ?? undefined,
  });
  if (!q.success) {
    return new Response(JSON.stringify({ error: q.error.flatten() }), { status: 400 });
  }
  const page = q.data.page ?? 1;
  const pageSize = q.data.pageSize ?? 20;
  const data = await entriesByLanguage(p.data.id, page, pageSize);
  return new Response(JSON.stringify(data), { headers: { "content-type": "application/json" } });
}

export const runtime = "nodejs";
