/**
 * POST /api/competitors/add — add a competitor + trigger initial crawl.
 */

import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { crawlAndSnapshot } from "@/lib/services/competitor-monitor";

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

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

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

  const domain = body.domain.trim().replace(/^https?:\/\//, "").replace(/\/$/, "").toLowerCase();
  const competitor = await prisma.competitor.upsert({
    where: { brandId_domain: { brandId: body.brandId, domain } },
    create: { brandId: body.brandId, domain, name: body.name || domain, isActive: true },
    update: { isActive: true, name: body.name || undefined },
  });

  // Initial crawl (best effort)
  let snapshot = null;
  try { snapshot = await crawlAndSnapshot(competitor.id, body.brandId); } catch { /* swallow */ }

  return NextResponse.json({ competitor, snapshot });
}
