/**
 * POST /api/admin/demo-brand/seed/ai-attribution
 * ─────────────────────────────────────────────────
 * Phase 2 seed: AiAttribution records
 *
 * Generates ~3,000 AI referral sessions across ChatGPT, Perplexity,
 * Google AI Overviews, Claude, and Gemini over 120 days with a
 * realistic growth trend (AI traffic growing faster than organic).
 *
 * 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;

const AI_PLATFORMS = [
  { platform: "chatgpt",             channel: "llmo" },
  { platform: "chatgpt",             channel: "llmo" },
  { platform: "perplexity",          channel: "llmo" },
  { platform: "google_ai_overview",  channel: "geo" },
  { platform: "google_ai_overview",  channel: "geo" },
  { platform: "gemini",              channel: "geo" },
  { platform: "claude",              channel: "aeo" },
  { platform: "copilot",             channel: "aeo" },
];

const LANDING_PAGES = [
  "/services/cardiac-care/", "/services/electrophysiology/",
  "/appointments/", "/about/our-team/", "/locations/houston/",
  "/blog/heart-health-tips/", "/blog/managing-atrial-fibrillation/",
];

const QUERY_CONTEXTS = [
  "best cardiologist in Houston Texas",
  "top heart doctors Houston",
  "cardiac care specialist near me",
  "who are the best cardiologists in Sugar Land TX",
  "heart failure specialist Houston",
  "atrial fibrillation treatment centers Houston",
  "cardiologist accepting new patients Houston",
  "preventive cardiology Houston",
];

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

function pick<T>(arr: T[], day: number, idx: number, salt: number): T {
  return arr[Math.floor(seeded(day * 1000 + idx, salt) * arr.length)];
}

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 } });
  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 rows: Array<{
    brandId: string; sessionId: string; channel: string; aiPlatform: string;
    landingPage: string; queryContext: string | null; referrerUrl: string | null;
    pagesViewed: number; sessionDuration: number; engagementScore: number;
    converted: boolean; conversionType: string | null; timestamp: Date;
  }> = [];

  for (let dayBack = 119; dayBack >= 0; dayBack--) {
    const dayTs = now - dayBack * 86_400_000;
    const dayDate = new Date(dayTs);
    const dow = dayDate.getUTCDay();
    const isWeekend = dow === 0 || dow === 6;

    // AI traffic grows faster — from 0.5x to 1.3x over 120 days
    const growthFactor = 0.5 + (119 - dayBack) / 119 * 0.8;
    const weekdayMult = isWeekend ? 0.65 : 1.0;
    const aiPerDay = Math.round(25 * growthFactor * weekdayMult);

    for (let i = 0; i < aiPerDay; i++) {
      const hourOffset = Math.floor(seeded(dayBack * 1000 + i, 1) * 16 + 7) * 3600_000;
      const ts = new Date(dayTs + hourOffset - 14 * 3600_000);
      const ap = pick(AI_PLATFORMS, dayBack, i, 2);
      const landing = pick(LANDING_PAGES, dayBack, i, 3);
      const query = pick(QUERY_CONTEXTS, dayBack, i, 4);
      const pagesViewed = Math.floor(seeded(dayBack * 1000 + i, 5) * 4) + 1;
      const duration = pagesViewed * 42 + Math.floor(seeded(dayBack * 1000 + i, 6) * 120);
      const engaged = seeded(dayBack * 1000 + i, 7) > 0.3;
      const converted = seeded(dayBack * 1000 + i, 8) < 0.08; // ~8% AI conversion rate

      rows.push({
        brandId: body.brandId,
        sessionId: `ai_${brand.id.slice(-6)}_${dayBack}_${i}`,
        channel: ap.channel,
        aiPlatform: ap.platform,
        landingPage: `https://${brand.domain}${landing}`,
        queryContext: query,
        referrerUrl: ap.platform === "perplexity" ? "https://www.perplexity.ai/" : ap.platform === "chatgpt" ? "https://chat.openai.com/" : null,
        pagesViewed,
        sessionDuration: duration,
        engagementScore: engaged ? seeded(dayBack * 1000 + i, 9) * 0.4 + 0.6 : seeded(dayBack * 1000 + i, 9) * 0.4,
        converted,
        conversionType: converted ? (seeded(dayBack * 1000 + i, 10) > 0.5 ? "form_submit" : "phone_number_click") : null,
        timestamp: ts,
      });
    }
  }

  let total = 0;
  for (let i = 0; i < rows.length; i += BATCH) {
    await prisma.aiAttribution.createMany({ data: rows.slice(i, i + BATCH), skipDuplicates: true });
    total += Math.min(BATCH, rows.length - i);
  }

  console.info(`[demo-brand/seed/phase2] brand=${body.brandId} aiAttributions=${total}`);

  return NextResponse.json({ ok: true, phase: "ai-attribution", created: { aiAttributions: total } });
}
