import { NextRequest } from "next/server";
import { z } from "zod";
import { searchReleases } from "@/server/repo";
import { parseIdList } from "@/utils/params";

const querySchema = z.object({
  q: z.string().optional(),
  page: z.coerce.number().int().positive().optional(),
  pageSize: z.coerce.number().int().positive().max(100).optional(),
  year: z.coerce.number().int().optional(),
  sort: z.enum(["year_desc", "year_asc", "title", "entry_id_desc"]).optional(),
  dLanguageId: z.string().trim().length(2).optional(),
  dMachinetypeId: z.string().optional(),
  filetypeId: z.coerce.number().int().positive().optional(),
  schemetypeId: z.string().trim().length(2).optional(),
  sourcetypeId: z.string().trim().length(1).optional(),
  casetypeId: z.string().trim().length(1).optional(),
  isDemo: z.coerce.boolean().optional(),
});

export async function GET(req: NextRequest) {
  const { searchParams } = new URL(req.url);
  const parsed = querySchema.safeParse({
    q: searchParams.get("q") ?? undefined,
    page: searchParams.get("page") ?? undefined,
    pageSize: searchParams.get("pageSize") ?? undefined,
    year: searchParams.get("year") ?? undefined,
    sort: searchParams.get("sort") ?? undefined,
    dLanguageId: searchParams.get("dLanguageId") ?? undefined,
    dMachinetypeId: searchParams.get("dMachinetypeId") ?? undefined,
    filetypeId: searchParams.get("filetypeId") ?? undefined,
    schemetypeId: searchParams.get("schemetypeId") ?? undefined,
    sourcetypeId: searchParams.get("sourcetypeId") ?? undefined,
    casetypeId: searchParams.get("casetypeId") ?? undefined,
    isDemo: searchParams.get("isDemo") ?? undefined,
  });
  if (!parsed.success) {
    return new Response(JSON.stringify({ error: parsed.error.flatten() }), {
      status: 400,
      headers: { "content-type": "application/json" },
    });
  }
  const dMachinetypeId = parseIdList(parsed.data.dMachinetypeId);
  const data = await searchReleases({ ...parsed.data, dMachinetypeId });
  return new Response(JSON.stringify(data), {
    headers: { "content-type": "application/json" },
  });
}

export const runtime = "nodejs";
