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

export async function GET() {
  const rows = await prisma.partnerRequest.findMany({
    where: { status: "approved" },
    orderBy: [{ active: "desc" }, { sortOrder: "asc" }, { createdAt: "desc" }],
    select: { id: true, region: true, name: true, address: true, imageUrl: true, sortOrder: true, active: true },
  });
  return NextResponse.json({ items: rows });
}

const createSchema = z.object({
  region: z.string().min(1),
  name: z.string().min(1),
  address: z.string().min(1),
  imageUrl: z.string().min(1),
  sortOrder: z.coerce.number().int().optional(),
  active: z.boolean().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 item = await prisma.partnerRequest.create({ data: { ...(parsed.data as any), status: "approved" } });
  return NextResponse.json({ item }, { status: 201 });
}


