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

export async function GET() {
  try {
    // 정렬용 컬럼(sortOrder)이 있는 경우 우선 사용
    const partners = await (prisma as any).partner.findMany({ orderBy: [{ sortOrder: "asc" }, { createdAt: "desc" }] });
    return NextResponse.json({ partners });
  } catch (_) {
    // 컬럼이 아직 DB에 없으면 createdAt 기준으로 폴백
    const partners = await prisma.partner.findMany({ orderBy: { createdAt: "desc" } });
    return NextResponse.json({ partners });
  }
}

const createSchema = z.object({
  name: z.string().min(1),
  category: z.string().min(1),
  latitude: z.coerce.number(),
  longitude: z.coerce.number(),
  address: z.string().min(1).optional(),
  imageUrl: z
    .string()
    .refine((v) => !v || /^https?:\/\//.test(v) || v.startsWith("/"), {
      message: "imageUrl must be http(s) URL or start with /",
    })
    .optional(),
  sortOrder: z.coerce.number().int().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 partner = await prisma.partner.create({ data: parsed.data as any });
  return NextResponse.json({ partner }, { status: 201 });
}


