/**
 * PUT    /api/alerts/rules/[id] — update
 * DELETE /api/alerts/rules/[id] — delete
 */
import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";

export const dynamic = "force-dynamic";

async function resolve(id: string, userId: string) {
  const rule = await prisma.alertRule.findUnique({ where: { id }, include: { brand: { include: { organization: { include: { memberships: true } } } } } });
  if (!rule) return { error: "Not found" as const, status: 404 };
  if (!rule.brand.organization.memberships.some((m) => m.userId === userId)) return { error: "Access denied" as const, status: 403 };
  return { rule };
}

export async function PUT(req: Request, { params }: { params: { id: string } }) {
  const user = await getCurrentUser();
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  const r = await resolve(params.id, user.id);
  if ("error" in r) return NextResponse.json({ error: r.error }, { status: r.status });
  const body = await req.json().catch(() => ({})) as Record<string, unknown>;

  const updated = await prisma.alertRule.update({
    where: { id: params.id },
    data: {
      name: typeof body.name === "string" ? body.name : undefined,
      type: typeof body.type === "string" ? body.type : undefined,
      condition: body.condition ? body.condition as object : undefined,
      channels: Array.isArray(body.channels) ? body.channels as string[] : undefined,
      recipients: Array.isArray(body.recipients) ? body.recipients as string[] : undefined,
      smsRecipients: Array.isArray(body.smsRecipients) ? body.smsRecipients as string[] : undefined,
      severity: typeof body.severity === "string" ? body.severity : undefined,
      isActive: typeof body.isActive === "boolean" ? body.isActive : undefined,
      cooldownMinutes: typeof body.cooldownMinutes === "number" ? body.cooldownMinutes : undefined,
    },
  });
  return NextResponse.json({ rule: updated });
}

export async function DELETE(_req: Request, { params }: { params: { id: string } }) {
  const user = await getCurrentUser();
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  const r = await resolve(params.id, user.id);
  if ("error" in r) return NextResponse.json({ error: r.error }, { status: r.status });
  await prisma.alertRule.delete({ where: { id: params.id } });
  return NextResponse.json({ ok: true });
}
