/**
 * Multi-Session AI Attribution
 * ─────────────────────────────
 * Checks if a converting visitor had a prior AI-referred session.
 * Enables "AI-assisted" attribution: AI awareness → organic return → conversion.
 */

import { prisma } from "@/lib/prisma";

export interface MultiSessionResult {
  hasAiTouch: boolean;
  touchType: "direct" | "assisted" | "none";
  aiSession?: {
    sessionId: string;
    platform: string;
    channel: string;
    landingPage: string;
    timestamp: Date;
    daysBetween: number;
  };
}

export async function checkMultiSessionAiTouch(
  brandId: string,
  visitorId: string,
  conversionSessionId: string,
): Promise<MultiSessionResult> {
  if (!visitorId || visitorId === "anon") {
    return { hasAiTouch: false, touchType: "none" };
  }

  return prisma.$transaction(async (tx) => {
    // Check if the converting session itself is AI-referred
    const directAttribution = await tx.aiAttribution.findFirst({
      where: { brandId, sessionId: conversionSessionId },
      select: { id: true },
    });
    if (directAttribution) {
      return { hasAiTouch: true, touchType: "direct" } satisfies MultiSessionResult;
    }

    // Find prior sessions via SiteConversion's visitorId
    const priorConversions = await tx.siteConversion.findMany({
      where: {
        brandId,
        visitorId,
        sessionId: { not: conversionSessionId },
      },
      orderBy: { timestamp: "desc" },
      take: 20,
      select: { sessionId: true, timestamp: true },
      distinct: ["sessionId"],
    });
    const priorSessions = priorConversions.map((c) => ({
      sessionId: c.sessionId,
      startedAt: c.timestamp,
    }));

    if (priorSessions.length === 0) {
      return { hasAiTouch: false, touchType: "none" } satisfies MultiSessionResult;
    }

    // Check if any prior session has an AI attribution
    const priorSessionIds = priorSessions.map((s) => s.sessionId);
    const priorAi = await tx.aiAttribution.findFirst({
      where: { brandId, sessionId: { in: priorSessionIds } },
      orderBy: { timestamp: "desc" },
      select: {
        sessionId: true,
        aiPlatform: true,
        channel: true,
        landingPage: true,
        timestamp: true,
      },
    });

    if (!priorAi) {
      return { hasAiTouch: false, touchType: "none" } satisfies MultiSessionResult;
    }

    const daysBetween = Math.round(
      (Date.now() - priorAi.timestamp.getTime()) / 86_400_000,
    );

    // Create an assisted attribution record
    await tx.aiAttribution.create({
      data: {
        brandId,
        sessionId: conversionSessionId,
        channel: priorAi.channel,
        aiPlatform: priorAi.aiPlatform,
        landingPage: priorAi.landingPage,
        queryContext: `[assisted] AI touch ${daysBetween}d ago via ${priorAi.aiPlatform ?? "unknown"}`,
        converted: true,
      },
    });

    return {
      hasAiTouch: true,
      touchType: "assisted",
      aiSession: {
        sessionId: priorAi.sessionId,
        platform: priorAi.aiPlatform ?? "unknown",
        channel: priorAi.channel,
        landingPage: priorAi.landingPage,
        timestamp: priorAi.timestamp,
        daysBetween,
      },
    } satisfies MultiSessionResult;
  }, { timeout: 5000, maxWait: 1000 });
}
