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

export async function GET() {
  const banners = await prisma.banner.findMany({ orderBy: [{ active: "desc" }, { sortOrder: "asc" }, { createdAt: "desc" }] });
  return NextResponse.json({ banners });
}

const createSchema = z.object({
  title: z.string().min(1),
  // 절대 URL 또는 /로 시작하는 상대경로 허용
  imageUrl: z.string().refine((v) => /^https?:\/\//.test(v) || v.startsWith("/"), {
    message: "imageUrl must be absolute URL or start with /",
  }),
  linkUrl: z.string().refine((v) => !v || /^https?:\/\//.test(v), { message: "linkUrl must be http(s) URL" }).optional(),
  active: z.boolean().optional(),
  sortOrder: z.coerce.number().int().optional(),
  startAt: z.coerce.date().optional(),
  endAt: z.coerce.date().optional(),
});

export async function POST(req: Request) {
  const body = await req.json().catch(() => ({}));
  const parsed = createSchema.safeParse(body);
  if (!parsed.success) return NextResponse.json({ error: parsed.error.flatten() }, { status: 400 });
  const banner = await prisma.banner.create({ data: parsed.data });
  return NextResponse.json({ banner }, { status: 201 });
}


