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

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

// GET /api/channels — list marketing channels (any signed-in user, for the
// KPI multi-select).
export const GET = withGuard(async () => {
  await requireUser();
  const channels = await prisma.marketingChannel.findMany({ orderBy: { name: "asc" } });
  return ok(channels);
});

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