import { NextRequest, NextResponse } from "next/server";
import { z } from "zod";
import { db, ingredients, asc } from "@epicure/db";
import { requireAdmin } from "@/lib/api-auth";

const Schema = z.object({
  name: z.string().trim().min(1).max(100),
  aliases: z.array(z.string().trim().min(1).max(100)).max(50).default([]),
  category: z.string().max(50).optional(),
});

export async function GET() {
  const { response } = await requireAdmin();
  if (response) return response;

  const rows = await db.select().from(ingredients).orderBy(asc(ingredients.name));
  return NextResponse.json({ data: rows });
}

export async function POST(req: NextRequest) {
  const { response } = await requireAdmin();
  if (response) return response;

  const parsed = Schema.safeParse(await req.json().catch(() => null));
  if (!parsed.success) return NextResponse.json({ error: "Validation error" }, { status: 400 });

  const id = crypto.randomUUID();
  try {
    await db.insert(ingredients).values({
      id,
      name: parsed.data.name,
      aliases: parsed.data.aliases,
      category: parsed.data.category,
    });
  } catch {
    return NextResponse.json({ error: "An ingredient with this name already exists" }, { status: 409 });
  }

  return NextResponse.json({ id }, { status: 201 });
}
