import { prisma } from "@/lib/prisma";
import { requireUser, requirePermission, withGuard } from "@/lib/guard";
import { parseBody, ok } from "@/lib/http";
import { platformSchema } from "@/lib/validators";

export const runtime = "nodejs";
export const dynamic = "force-dynamic";

// GET /api/platforms — list platforms (any signed-in user, for the post form).
export const GET = withGuard(async () => {
  await requireUser();
  const platforms = await prisma.platform.findMany({ orderBy: { name: "asc" } });
  return ok(platforms);
});

// POST /api/platforms — create a platform (Manager-tier and above).
export const POST = withGuard(async (req: Request) => {
  await requirePermission("platforms:write");
  const data = await parseBody(req, platformSchema);
  const name = data.name.trim();
  const exists = await prisma.platform.findUnique({ where: { name } });
  if (exists) return ok({ error: "Platform name already in use" }, 409);
  const platform = await prisma.platform.create({
    data: { name, active: data.active ?? true },
  });
  return ok(platform, 201);
});
