/**
 * POST /api/admin/demo-brand/seed/all-other-surfaces
 * ────────────────────────────────────────────────────
 * Phase 4 seed: TrackedKeyword + KeywordRanking, AiVisibilityQuery +
 * AiVisibilityCheck, Competitor + CompetitorPage, Backlink
 *
 * Seeds all sidebar surfaces not covered by phases 1–3 so every
 * page in the demo brand has realistic data to display.
 *
 * Auth: x-admin-secret header
 * Body: { brandId: string }
 */

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

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

const BATCH = 5000;

// ── Rank Tracker keywords ───────────────────────────────────────────
const TRACKED_KEYWORDS = [
  { keyword: "houston cardiologist",             location: "Houston, TX", device: "desktop", tags: ["branded", "local"] },
  { keyword: "cardiologist near me",             location: "Houston, TX", device: "mobile",  tags: ["local"] },
  { keyword: "heart specialist houston",         location: "Houston, TX", device: "desktop", tags: ["local"] },
  { keyword: "cardiac care houston",             location: "Houston, TX", device: "desktop", tags: ["local"] },
  { keyword: "atrial fibrillation treatment houston", location: "Houston, TX", device: "desktop", tags: ["service"] },
  { keyword: "cardiologist sugar land tx",       location: "Sugar Land, TX", device: "desktop", tags: ["local"] },
  { keyword: "heart failure specialist houston", location: "Houston, TX", device: "desktop", tags: ["service"] },
  { keyword: "cardiac imaging houston",          location: "Houston, TX", device: "desktop", tags: ["service"] },
  { keyword: "best cardiologist houston",        location: "Houston, TX", device: "desktop", tags: ["branded", "local"] },
  { keyword: "preventive cardiology houston",    location: "Houston, TX", device: "desktop", tags: ["service"] },
  { keyword: "electrophysiology houston",        location: "Houston, TX", device: "desktop", tags: ["service"] },
  { keyword: "heart doctor houston texas",       location: "Houston, TX", device: "mobile",  tags: ["local"] },
];

// positions over 120 days (oldest → newest)
const KEYWORD_TRAJECTORIES: Record<string, { startPos: number; endPos: number }> = {
  "houston cardiologist":              { startPos: 6,  endPos: 3 },
  "cardiologist near me":              { startPos: 12, endPos: 8 },
  "heart specialist houston":          { startPos: 8,  endPos: 5 },
  "cardiac care houston":              { startPos: 15, endPos: 12 },
  "atrial fibrillation treatment houston": { startPos: 9, endPos: 6 },
  "cardiologist sugar land tx":        { startPos: 4,  endPos: 2 },
  "heart failure specialist houston":  { startPos: 11, endPos: 9 },
  "cardiac imaging houston":           { startPos: 7,  endPos: 6 },
  "best cardiologist houston":         { startPos: 5,  endPos: 4 },
  "preventive cardiology houston":     { startPos: 18, endPos: 14 },
  "electrophysiology houston":         { startPos: 7,  endPos: 5 },
  "heart doctor houston texas":        { startPos: 9,  endPos: 7 },
};

// ── AI Visibility queries ───────────────────────────────────────────
const AI_QUERIES = [
  { query: "best cardiologist in Houston Texas",          category: "local",       intent: "commercial" },
  { query: "top heart doctors Houston",                   category: "local",       intent: "commercial" },
  { query: "cardiac care specialist recommendations",     category: "general",     intent: "informational" },
  { query: "who are the best cardiologists near me",      category: "local",       intent: "commercial" },
  { query: "heart failure treatment options Houston",     category: "local",       intent: "informational" },
  { query: "atrial fibrillation treatment centers",       category: "service",     intent: "commercial" },
  { query: "cardiac imaging centers Houston",             category: "service",     intent: "commercial" },
  { query: "electrophysiology specialist Texas",          category: "general",     intent: "informational" },
];

const AI_PLATFORMS = ["chatgpt", "perplexity", "gemini", "claude"] as const;

// ── Competitors ─────────────────────────────────────────────────────
const COMPETITORS = [
  {
    domain: "texasheart.org",
    name: "Texas Heart Institute",
    pages: [
      { url: "https://texasheart.org/heart-health/", title: "Heart Health", wordCount: 2400 },
      { url: "https://texasheart.org/services/cardiac-surgery/", title: "Cardiac Surgery", wordCount: 1800 },
      { url: "https://texasheart.org/services/electrophysiology/", title: "Electrophysiology", wordCount: 1600 },
      { url: "https://texasheart.org/services/preventive-cardiology/", title: "Preventive Cardiology", wordCount: 1400 },
      { url: "https://texasheart.org/contact/", title: "Contact", wordCount: 300 },
    ],
  },
  {
    domain: "memorialhermann.org",
    name: "Memorial Hermann",
    pages: [
      { url: "https://memorialhermann.org/services/specialties/heart/", title: "Heart & Vascular", wordCount: 2100 },
      { url: "https://memorialhermann.org/services/specialties/heart/cardiac-imaging/", title: "Cardiac Imaging", wordCount: 1500 },
      { url: "https://memorialhermann.org/services/specialties/heart/heart-failure/", title: "Heart Failure", wordCount: 1700 },
      { url: "https://memorialhermann.org/locations/", title: "Locations", wordCount: 400 },
    ],
  },
];

// ── Backlinks ────────────────────────────────────────────────────────
const BACKLINK_SOURCES = [
  { url: "https://www.healthgrades.com/practice/heartwell-cardiology", domain: "healthgrades.com", anchor: "Heartwell Cardiology", dr: 82 },
  { url: "https://www.zocdoc.com/practice/heartwell-cardiology-houston", domain: "zocdoc.com", anchor: "Heartwell Cardiology Houston", dr: 79 },
  { url: "https://www.vitals.com/doctors/heartwell-cardiology", domain: "vitals.com", anchor: "cardiologists in Houston", dr: 61 },
  { url: "https://www.usnews.com/best-hospitals/houston-cardiology", domain: "usnews.com", anchor: "top cardiac care Houston", dr: 91 },
  { url: "https://houston.culturemap.com/news/health/heartwell", domain: "culturemap.com", anchor: "Heart health Houston", dr: 55 },
  { url: "https://www.yelp.com/biz/heartwell-cardiology-houston", domain: "yelp.com", anchor: "Heartwell Cardiology reviews", dr: 93 },
  { url: "https://www.facebook.com/heartwellcardiology", domain: "facebook.com", anchor: "Heartwell Cardiology Facebook", dr: 100 },
  { url: "https://www.bbb.org/us/tx/houston/heartwell-cardiology", domain: "bbb.org", anchor: "BBB profile", dr: 86 },
];

function seeded(n: number, salt: number): number {
  const x = Math.sin(n * 9301 + salt * 49297 + 233) * 100003;
  return Math.abs(x - Math.floor(x));
}

export async function POST(req: Request) {
  const secret = req.headers.get("x-admin-secret");
  if (!secret || secret !== process.env.ADMIN_SECRET) {
    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 });

  const brand = await prisma.brand.findUnique({ where: { id: body.brandId }, select: { id: true, isDemo: true, domain: true, orgId: true } });
  if (!brand) return NextResponse.json({ error: "Brand not found" }, { status: 404 });
  if (!brand.isDemo) return NextResponse.json({ error: "Brand is not a demo brand — seed refused" }, { status: 403 });

  const now = Date.now();
  const counts = { trackedKeywords: 0, keywordRankings: 0, aiQueries: 0, aiChecks: 0, competitors: 0, competitorPages: 0, backlinks: 0 };

  // ── 1. TrackedKeywords + KeywordRanking history ──────────────────
  for (const kw of TRACKED_KEYWORDS) {
    const tk = await prisma.trackedKeyword.upsert({
      where: { brandId_keyword_location_device: { brandId: body.brandId, keyword: kw.keyword, location: kw.location, device: kw.device } },
      update: { isActive: true },
      create: { brandId: body.brandId, keyword: kw.keyword, location: kw.location, device: kw.device, tags: kw.tags, isActive: true },
    });
    counts.trackedKeywords++;

    const traj = KEYWORD_TRAJECTORIES[kw.keyword] ?? { startPos: 10, endPos: 7 };
    const rankingRows: Array<{ trackedKeywordId: string; position: number; previousPosition: number | null; url: string; searchVolume: number; serpFeatures: string[]; source: string; checkedAt: Date }> = [];

    // Monthly check points over 120 days
    for (let dayBack = 119; dayBack >= 0; dayBack -= 7) {
      const progress = (119 - dayBack) / 119;
      const pos = Math.round(traj.startPos + (traj.endPos - traj.startPos) * progress + (seeded(dayBack + kw.keyword.length, 1) - 0.5) * 2);
      const prevDayBack = dayBack + 7;
      const prevProgress = Math.min(1, (119 - prevDayBack) / 119);
      const prevPos = Math.round(traj.startPos + (traj.endPos - traj.startPos) * prevProgress + (seeded(prevDayBack + kw.keyword.length, 1) - 0.5) * 2);

      rankingRows.push({
        trackedKeywordId: tk.id,
        position: Math.max(1, pos),
        previousPosition: Math.max(1, prevPos),
        url: `https://${brand.domain}/services/cardiac-care/`,
        searchVolume: Math.round(1200 + seeded(dayBack, 2) * 800),
        serpFeatures: ["local_pack", "reviews"],
        source: "dataforseo",
        checkedAt: new Date(now - dayBack * 86_400_000),
      });
    }

    for (let i = 0; i < rankingRows.length; i += BATCH) {
      await prisma.keywordRanking.createMany({ data: rankingRows.slice(i, i + BATCH), skipDuplicates: true });
    }
    counts.keywordRankings += rankingRows.length;
  }

  // ── 2. AI Visibility queries + checks ───────────────────────────
  for (const q of AI_QUERIES) {
    const aq = await prisma.aiVisibilityQuery.upsert({
      where: { brandId_query: { brandId: body.brandId, query: q.query } },
      update: { isActive: true },
      create: { brandId: body.brandId, query: q.query, category: q.category, isActive: true },
    });
    counts.aiQueries++;

    const checkRows: Array<{ brandId: string; query: string; platform: string; mentioned: boolean; position: number | null; sentiment: string | null; checkedAt: Date }> = [];

    for (const platform of AI_PLATFORMS) {
      // Bi-weekly checks over 120 days
      for (let dayBack = 119; dayBack >= 0; dayBack -= 14) {
        const mentioned = seeded(dayBack + q.query.length + platform.length, 3) > 0.35;
        const position = mentioned ? Math.floor(seeded(dayBack, 4) * 4) + 1 : null;
        const sentiment = mentioned ? (seeded(dayBack, 5) > 0.7 ? "positive" : "neutral") : null;
        checkRows.push({
          brandId: body.brandId,
          query: q.query,
          platform,
          mentioned,
          position,
          sentiment,
          checkedAt: new Date(now - dayBack * 86_400_000),
        });
      }
    }

    for (let i = 0; i < checkRows.length; i += BATCH) {
      await prisma.aiVisibilityCheck.createMany({ data: checkRows.slice(i, i + BATCH), skipDuplicates: true });
    }
    counts.aiChecks += checkRows.length;
  }

  // ── 3. Competitors + CompetitorPages ────────────────────────────
  for (const comp of COMPETITORS) {
    const competitor = await prisma.competitor.upsert({
      where: { brandId_domain: { brandId: body.brandId, domain: comp.domain } },
      update: { isActive: true },
      create: { brandId: body.brandId, domain: comp.domain, name: comp.name, isActive: true },
    });
    counts.competitors++;

    const pageRows = comp.pages.map((p) => ({
      competitorId: competitor.id,
      url: p.url,
      title: p.title,
      wordCount: p.wordCount,
      firstSeenAt: new Date(now - 60 * 86_400_000),
      lastCheckedAt: new Date(now - 2 * 86_400_000),
      status: "unchanged",
    }));

    for (let i = 0; i < pageRows.length; i += BATCH) {
      await prisma.competitorPage.createMany({ data: pageRows.slice(i, i + BATCH), skipDuplicates: true });
    }
    counts.competitorPages += pageRows.length;
  }

  // ── 4. Backlinks ─────────────────────────────────────────────────
  // Create BacklinkSnapshot first
  const snapshot = await prisma.backlinkSnapshot.create({
    data: {
      brandId: body.brandId,
      totalBacklinks: BACKLINK_SOURCES.length * 3,
      totalDomains: BACKLINK_SOURCES.length,
      newBacklinks: 12,
      lostBacklinks: 3,
      avgDomainAuthority: 78.5,
      snapshotDate: new Date(),
    },
  });

  const backlinkRows = BACKLINK_SOURCES.map((bl, i) => ({
    brandId: body.brandId as string,
    sourceUrl: bl.url,
    sourceDomain: bl.domain,
    targetUrl: `https://${brand.domain}/`,
    anchorText: bl.anchor,
    domainAuthority: bl.dr,
    linkType: "dofollow",
    status: "active",
    firstSeenAt: new Date(now - (90 + i * 5) * 86_400_000),
    lastSeenAt: new Date(now - i * 86_400_000),
  }));

  for (let i = 0; i < backlinkRows.length; i += BATCH) {
    await prisma.backlink.createMany({ data: backlinkRows.slice(i, i + BATCH), skipDuplicates: true });
  }
  counts.backlinks += backlinkRows.length;

  console.info(`[demo-brand/seed/phase4] brand=${body.brandId}`, counts);

  return NextResponse.json({ ok: true, phase: "all-other-surfaces", created: counts });
}
