import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { parseAffiliate } from "@/lib/dto";
import { guard, run, readBody } from "@/lib/adminRoute";

export async function GET() {
  const denied = await guard();
  if (denied) return denied;
  return run(async () => {
    const items = await prisma.affiliate.findMany({
      orderBy: [{ sortIndex: "asc" }, { createdAt: "asc" }],
    });
    return NextResponse.json(items);
  });
}

export async function POST(req: Request) {
  const denied = await guard();
  if (denied) return denied;
  return run(async () => {
    const data = parseAffiliate(await readBody(req));
    const created = await prisma.affiliate.create({ data });
    return NextResponse.json(created, { status: 201 });
  });
}
