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

export async function GET() {
  try {
    // 카테고리 조인 포함
    const partners = await (prisma as any).partner.findMany({ orderBy: [{ sortOrder: "asc" }, { createdAt: "desc" }], include: { categoryRef: true } });
    return NextResponse.json({ partners });
  } catch (_) {
    // 컬럼이 아직 DB에 없으면 createdAt 기준으로 폴백
    const partners = await prisma.partner.findMany({ orderBy: { createdAt: "desc" }, include: { categoryRef: true } });
    return NextResponse.json({ partners });
  }
}

const createSchema = z.object({
  name: z.string().min(1),
  category: z.string().min(1).optional(),
  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(),
  categoryId: z.string().min(1),
});

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 });
  try {
    const { categoryId } = parsed.data as any;
    const cat = await prisma.partnerCategory.findUnique({ where: { id: categoryId } });
    if (!cat) return NextResponse.json({ error: 'invalid_category', message: '유효하지 않은 카테고리입니다.' }, { status: 400 });
    const data: any = { ...parsed.data };
    if (!data.category) data.category = cat.name;
    const partner = await prisma.partner.create({ data });
    return NextResponse.json({ partner }, { status: 201 });
  } catch (e: any) {
    // Unique name 에러 처리
    if (e?.code === 'P2002') {
      return NextResponse.json({ error: 'duplicate_name', message: '이미 존재하는 업체명입니다.' }, { status: 409 });
    }
    return NextResponse.json({ error: 'unknown_error' }, { status: 500 });
  }
}


