import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";

/**
 * POST /api/content-briefs/links
 * Regenerate internal linking suggestions for a brief.
 * Body: { briefId: string }
 *
 * Returns the new links and saves them to the brief.
 */
export const dynamic = "force-dynamic";

export async function POST(req: Request) {
  const user = await getCurrentUser();
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  try {
    const { briefId } = await req.json();
    if (!briefId) return NextResponse.json({ error: "briefId is required" }, { status: 400 });

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

    const type = brief.type as "seo" | "llmo";

    // Generate links based on brief data
    const links = type === "seo"
      ? generateSeoLinksFromBrief(brief)
      : generateLlmoLinksFromBrief(brief);

    // Save to database
    await prisma.contentBrief.update({
      where: { id: briefId },
      data: { internalLinks: JSON.parse(JSON.stringify(links)) },
    });

    return NextResponse.json({ links, count: links.length });

  } catch {
    return NextResponse.json({ error: "Something went wrong" }, { status: 500 });
  }
}

// ─── Link generators ─────────────────────────────────────────────────────────

interface LinkSuggestion {
  anchorText: string;
  targetUrl: string;
  context: string;
  category: string;
}

function generateSeoLinksFromBrief(brief: {
  primaryKeyword: string | null;
  secondaryKeywords: string[];
  service: string | null;
  city: string | null;
  brandName: string | null;
  ctaOffer: string | null;
}): LinkSuggestion[] {
  const service = brief.service || "services";
  const sl = service.toLowerCase();
  const brand = brief.brandName || "our company";
  const city = brief.city || "";
  const cl = city.toLowerCase();
  const keyword = brief.primaryKeyword || sl;
  const links: LinkSuggestion[] = [];

  // Service keyword links
  links.push({ anchorText: keyword, targetUrl: "/services", context: "Primary keyword — link from H1 or intro", category: "service" });

  if (sl !== keyword) {
    links.push({ anchorText: sl, targetUrl: `/services/${sl.replace(/\s+/g, "-")}`, context: "Service name — link from description", category: "service" });
  }

  for (const kw of brief.secondaryKeywords.slice(0, 2)) {
    links.push({ anchorText: kw.toLowerCase(), targetUrl: `/services/${kw.toLowerCase().replace(/\s+/g, "-")}`, context: "Secondary keyword — place in H2", category: "service" });
  }

  links.push({ anchorText: "case studies", targetUrl: "/case-studies", context: "Proof anchor — results section", category: "service" });
  links.push({ anchorText: `about ${brand.split(" ")[0].toLowerCase()}`, targetUrl: "/about", context: "Trust anchor — about paragraph", category: "service" });

  // Location links
  if (city) {
    links.push({ anchorText: `${sl} in ${cl}`, targetUrl: `/locations/${cl.replace(/\s+/g, "-")}`, context: "Geo anchor — intro or location section", category: "location" });
    links.push({ anchorText: `${cl} ${sl}`, targetUrl: `/locations/${cl.replace(/\s+/g, "-")}`, context: "Location-first — H2 or body", category: "location" });
  }

  links.push({ anchorText: brief.ctaOffer?.toLowerCase() || "get a free consultation", targetUrl: "/contact", context: "CTA anchor — conclusion", category: "service" });

  return links;
}

function generateLlmoLinksFromBrief(brief: {
  primaryTopic: string | null;
  longTailKeywords: string[];
  conversationalPhrases: string[];
  relatedQuestions: string[];
  service: string | null;
  city: string | null;
  brandName: string | null;
}): LinkSuggestion[] {
  const service = brief.service || "services";
  const sl = service.toLowerCase();
  const brand = brief.brandName || "our company";
  const city = brief.city || "";
  const topic = brief.primaryTopic || sl;
  const links: LinkSuggestion[] = [];

  // Long-tail anchors
  links.push({ anchorText: `learn more about ${topic} and how it works`, targetUrl: "/services", context: "Conversational — insight section", category: "long-tail" });

  for (const kw of brief.longTailKeywords.slice(0, 2)) {
    links.push({ anchorText: kw.toLowerCase(), targetUrl: `/blog/${kw.toLowerCase().replace(/\s+/g, "-").slice(0, 40)}`, context: "Long-tail keyword anchor", category: "long-tail" });
  }

  // Conversational anchors
  links.push({ anchorText: `see how ${brand} helps businesses with ${sl}`, targetUrl: "/case-studies", context: "Narrative — answer section", category: "conversational" });
  links.push({ anchorText: `explore ${brand}'s approach to ${sl}${city ? ` in ${city.toLowerCase()}` : ""}`, targetUrl: "/about", context: "Conversational — after insight", category: "conversational" });

  for (const phrase of brief.conversationalPhrases.slice(0, 1)) {
    links.push({ anchorText: phrase.toLowerCase(), targetUrl: "/services", context: "Natural phrase — mirrors AI queries", category: "conversational" });
  }

  // Question-based anchors
  for (const q of brief.relatedQuestions.slice(0, 2)) {
    const anchor = q.toLowerCase().replace(/\?$/, "").trim();
    links.push({ anchorText: anchor, targetUrl: `/faq#${anchor.replace(/\s+/g, "-").slice(0, 40)}`, context: "Question anchor — matches AI search patterns", category: "question" });
  }

  links.push({ anchorText: `get personalized ${sl} recommendations from ${brand}`, targetUrl: "/contact", context: "Conversational CTA — summary section", category: "conversational" });

  return links;
}
