import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";

type GalleryCategory = "PROFISSIONAL" | "BASE" | "HISTORIA";

function parseCategory(v: string | null): GalleryCategory | null {
  if (!v) return null;
  const u = v.toUpperCase().trim();
  if (u === "BASE") return "BASE";
  if (u === "PROFISSIONAL") return "PROFISSIONAL";
  if (u === "HISTORIA") return "HISTORIA";
  return null;
}

function parseYear(v: string | null): number | null {
  if (!v) return null;
  const n = Number(v);
  if (!Number.isFinite(n)) return null;
  return n >= 0 ? n : null;
}

export async function GET(req: Request) {
  const url = new URL(req.url);
  const ano = parseYear(url.searchParams.get("ano"));
  const categoria = parseCategory(url.searchParams.get("categoria"));

  const where: any = {};
  if (ano !== null) where.year = ano;
  if (categoria) where.category = categoria;

  const items = await prisma.galleryImage.findMany({
    where,
    orderBy: { sortOrder: "asc" },
    select: {
      id: true,
      title: true,
      imageUrl: true,
      year: true,
      category: true,
    },
  });

  return NextResponse.json({ items });
}

