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

export const runtime = "nodejs";

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

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

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