/**
 * POST /api/pages/sitemap-crawl
 * GET  /api/pages/sitemap-crawl?brandId=X
 *
 * POST triggers a fresh sitemap crawl for the brand's own domain and
 * caches the result in SiteEvent (see brand-sitemap.ts). GET returns the
 * most recent cached crawl without triggering a refresh — used by the
 * Page Launch Tracker UI to check whether lastmod data is populated.
 *
 * Auth: the requesting user must belong to the brand's organization.
 */

import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import {
  crawlBrandSitemap,
  getCachedBrandSitemap,
} from "@/lib/services/brand-sitemap";

export const dynamic = "force-dynamic";
// Sitemap crawls can follow several child sitemaps with 150ms polite
// delays between each — allow headroom over the default 10s.
export const maxDuration = 60;

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 { brandId?: string } | null;
  const brandId = body?.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 domain = resolved.brand.domain;
  if (!domain) return NextResponse.json({ error: "Brand has no domain configured" }, { status: 400 });

  try {
    const result = await crawlBrandSitemap(brandId, domain);
    return NextResponse.json({
      count: result.count,
      crawledAt: result.crawledAt,
      sitemapUrls: result.sitemapUrls,
      detectedCms: result.detectedCms,
    });
  } catch (err) {
    return NextResponse.json(
      { error: err instanceof Error ? err.message : "Crawl failed" },
      { status: 500 },
    );
  }
}

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 cache = await getCachedBrandSitemap(brandId);
  if (!cache) return NextResponse.json({ cache: null });
  return NextResponse.json({
    cache: {
      count: cache.count,
      crawledAt: cache.crawledAt,
      sitemapUrls: cache.sitemapUrls,
      detectedCms: cache.detectedCms,
    },
  });
}
