/**
 * POST /api/signals/detect  Body: { brandId: string }
 * GET  /api/signals/detect?brandId=X — same, for convenience
 * ──────────────────────────────────────────────────────────
 * On-demand signal detection for a brand. Typically called when the
 * Signals Center page loads so the user sees up-to-the-minute alerts
 * without waiting for the 6-hour cron cycle.
 *
 * Rate-limited to once per hour per brand via an in-memory Map. Vercel
 * cold-starts drop the cache (acceptable — the worst case is a second
 * run after a cold boot, which still hits the detector's idempotent
 * dedup path).
 */

import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { runAndPersistSignals, type PersistSummary } from "@/lib/services/signal-detection";

export const dynamic = "force-dynamic";
export const maxDuration = 60;

const CACHE_TTL_MS = 60 * 60 * 1000;
const cache = new Map<string, { summary: PersistSummary; cachedAt: number }>();

async function handle(brandId: string, userId: string) {
  // Authorise — user must belong to the brand's organisation.
  const brand = await prisma.brand.findUnique({
    where: { id: brandId },
    include: { organization: { include: { memberships: true } } },
  });
  if (!brand || !brand.organization.memberships.some((m) => m.userId === userId)) {
    return NextResponse.json({ error: "Access denied" }, { status: 403 });
  }

  const cached = cache.get(brandId);
  if (cached && Date.now() - cached.cachedAt < CACHE_TTL_MS) {
    return NextResponse.json({ ...cached.summary, cached: true, cachedAt: cached.cachedAt });
  }

  const summary = await runAndPersistSignals(brandId);
  cache.set(brandId, { summary, cachedAt: Date.now() });
  return NextResponse.json({ ...summary, cached: false });
}

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 { brandId?: string } | null;
  if (!body?.brandId) return NextResponse.json({ error: "brandId required" }, { status: 400 });
  return handle(body.brandId, user.id);
}

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 });
  return handle(brandId, user.id);
}
