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

export const runtime = "nodejs";

type Ctx = { params: Promise<{ id: string }> };

// PATCH /api/platforms/[id] — rename / (de)activate (Manager-tier and above).
export const PATCH = withGuard(async (req: Request, ctx: Ctx) => {
  await requirePermission("platforms:write");
  const { id } = await ctx.params;
  const data = await parseBody(req, platformSchema.partial());
  const platform = await prisma.platform
    .update({
      where: { id },
      data: {
        ...(data.name !== undefined && { name: data.name.trim() }),
        ...(data.active !== undefined && { active: data.active }),
      },
    })
    .catch(() => {
      throw new HttpError(404, "Platform not found");
    });
  return ok(platform);
});

// DELETE /api/platforms/[id] — remove a platform (detaches it from any posts).
export const DELETE = withGuard(async (_req: Request, ctx: Ctx) => {
  await requirePermission("platforms:write");
  const { id } = await ctx.params;
  await prisma.platform.delete({ where: { id } }).catch(() => {
    throw new HttpError(404, "Platform not found");
  });
  return ok({ ok: true });
});
