/**
 * POST /api/alerts/rules — create alert rule
 * GET  /api/alerts/rules?brandId=X — list alert rules
 */
import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";

export const dynamic = "force-dynamic";

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

export async function POST(req: Request) {
  const user = await getCurrentUser();
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  const body = await req.json().catch(() => null) as Record<string, unknown> | null;
  if (!body?.brandId || !body?.name || !body?.type) return NextResponse.json({ error: "brandId, name, type required" }, { status: 400 });

  const resolved = await authBrand(String(body.brandId), user.id);
  if ("error" in resolved) return NextResponse.json({ error: resolved.error }, { status: resolved.status });

  const rule = await prisma.alertRule.create({
    data: {
      brandId: String(body.brandId), name: String(body.name), type: String(body.type),
      condition: (body.condition ?? {}) as object,
      channels: Array.isArray(body.channels) ? body.channels as string[] : ["in_app"],
      recipients: Array.isArray(body.recipients) ? body.recipients as string[] : [],
      smsRecipients: Array.isArray(body.smsRecipients) ? body.smsRecipients as string[] : [],
      severity: String(body.severity || "medium"),
      cooldownMinutes: Number(body.cooldownMinutes || 60),
    },
  });
  return NextResponse.json({ rule });
}

export async function GET(req: Request) {
  const user = await getCurrentUser();
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  const brandId = new URL(req.url).searchParams.get("brandId");
  if (!brandId) return NextResponse.json({ error: "brandId required" }, { status: 400 });
  const resolved = await authBrand(brandId, user.id);
  if ("error" in resolved) return NextResponse.json({ error: resolved.error }, { status: resolved.status });

  const rules = await prisma.alertRule.findMany({ where: { brandId }, orderBy: { createdAt: "asc" } });
  return NextResponse.json({ rules });
}
