/**
 * POST /api/site-tag/ai-session
 *
 * Receives AI session behavioral profile from t.js on session end.
 * Processes engagement data, runs probabilistic AI model for unknown
 * referrers, and updates AiAttribution records.
 *
 * Ingest endpoint — no Clerk auth, CORS-enabled.
 */

import { NextResponse } from "next/server";
import { getCorsHeaders, resolveSiteFromTag } from "@/lib/services/page-lifecycle";
import { prisma } from "@/lib/prisma";
import { calculateAiProbability, calculateEngagementScore } from "@/lib/services/ai-behavioral-model";

export const dynamic = "force-dynamic";

export async function OPTIONS(req: Request) {
  return new NextResponse(null, { status: 204, headers: getCorsHeaders(req) });
}

export async function POST(req: Request) {
  const cors = getCorsHeaders(req);
  let body: Record<string, unknown>;
  try { body = await req.json(); } catch {
    return NextResponse.json({ ok: false }, { status: 200, headers: cors });
  }

  const siteId = body.siteId as string;
  const resolved = await resolveSiteFromTag(siteId, body.pageUrl as string);
  if (!resolved.ok) {
    return NextResponse.json({ ok: false, dropped: true }, { status: 200, headers: cors });
  }

  const brandId = resolved.site.brandId;
  const sessionId = typeof body.sessionId === "string" ? body.sessionId : null;
  if (!sessionId) {
    return NextResponse.json({ ok: false }, { status: 200, headers: cors });
  }

  const profile = (body.metadata ?? body) as Record<string, unknown>;
  const isAiReferred = profile.aiReferred === true;

  try {
    const engagementScore = calculateEngagementScore({
      pagesViewed: typeof profile.pagesViewed === "number" ? profile.pagesViewed : 1,
      dwellTime: typeof profile.dwellTime === "number" ? profile.dwellTime : 0,
      maxScroll: typeof profile.maxScroll === "number" ? profile.maxScroll : 0,
      converted: profile.formSubmitted === true || (typeof profile.phoneClicks === "number" && profile.phoneClicks > 0),
    });

    if (isAiReferred) {
      // Update existing AiAttribution with engagement data
      await prisma.aiAttribution.updateMany({
        where: { brandId, sessionId },
        data: {
          pagesViewed: typeof profile.pagesViewed === "number" ? profile.pagesViewed : 1,
          sessionDuration: typeof profile.dwellTime === "number" ? Math.round(profile.dwellTime / 1000) : null,
          maxScrollDepth: typeof profile.maxScroll === "number" ? profile.maxScroll : null,
          engagementScore,
        },
      });
    } else {
      // Run probabilistic AI model for non-AI-referred sessions
      const aiScore = calculateAiProbability({
        landingPage: typeof profile.landingPage === "string" ? profile.landingPage : "/",
        landingDepth: typeof profile.landingDepth === "number" ? profile.landingDepth : 0,
        maxScroll: typeof profile.maxScroll === "number" ? profile.maxScroll : 0,
        dwellTime: typeof profile.dwellTime === "number" ? profile.dwellTime : 0,
        firstInteractionAt: typeof profile.firstInteractionAt === "number" ? profile.firstInteractionAt : 0,
        textSelected: profile.textSelected === true,
        pagesViewed: typeof profile.pagesViewed === "number" ? profile.pagesViewed : 1,
        rageClicks: typeof profile.rageClicks === "number" ? profile.rageClicks : 0,
        returnVisitor: profile.returnVisitor === true,
        formSubmitted: profile.formSubmitted === true,
        phoneClicks: typeof profile.phoneClicks === "number" ? profile.phoneClicks : 0,
        searchTerms: Array.isArray(profile.searchTerms) ? profile.searchTerms as string[] : [],
        referrer: null,
      });

      // Create probable AI attribution for medium+ confidence
      if (aiScore.channel) {
        await prisma.aiAttribution.create({
          data: {
            brandId,
            sessionId,
            channel: aiScore.channel,
            aiPlatform: "behavioral_model",
            landingPage: typeof profile.landingPage === "string" ? profile.landingPage : "/",
            queryContext: `[inferred] Score: ${aiScore.score}/100, Signals: ${aiScore.signals.join(", ")}`,
            pagesViewed: typeof profile.pagesViewed === "number" ? profile.pagesViewed : 1,
            sessionDuration: typeof profile.dwellTime === "number" ? Math.round(profile.dwellTime / 1000) : null,
            maxScrollDepth: typeof profile.maxScroll === "number" ? profile.maxScroll : null,
            engagementScore,
            converted: profile.formSubmitted === true || (typeof profile.phoneClicks === "number" && profile.phoneClicks > 0),
            conversionType: profile.formSubmitted === true ? "form_submit" : (typeof profile.phoneClicks === "number" && profile.phoneClicks > 0) ? "click_to_call" : null,
          },
        });
      }
    }
  } catch (err) {
    console.error("[ai-session] processing failed:", err instanceof Error ? err.message : String(err));
  }

  return NextResponse.json({ ok: true }, { status: 200, headers: cors });
}
