/**
 * Competitor AI Citation Tracking
 * ────────────────────────────────
 * Tracks which competitors appear in AI citations alongside the brand.
 * Generates competitive signals and battle indicators.
 */

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

export interface AiCompetitiveLandscape {
  keyword: string;
  brandCited: boolean;
  brandPosition: number | null;
  competitors: Array<{
    domain: string;
    position: number;
  }>;
  battleStatus: "brand_wins" | "competitor_wins" | "both_cited" | "neither";
}

export async function getCompetitorAiLandscape(
  brandId: string,
  since: Date,
): Promise<AiCompetitiveLandscape[]> {
  const citations = await prisma.aiCitation.findMany({
    where: { brandId, checkedAt: { gte: since } },
    select: {
      keyword: true,
      brandCited: true,
      citedPosition: true,
      competitorsCited: true,
    },
    orderBy: { checkedAt: "desc" },
    distinct: ["keyword"],
  }).catch(() => []);

  return citations.map((c) => {
    const competitors: Array<{ domain: string; position: number }> = [];
    if (c.competitorsCited && typeof c.competitorsCited === "object") {
      const comps = c.competitorsCited as Array<{ domain?: string; position?: number }>;
      if (Array.isArray(comps)) {
        for (const comp of comps) {
          if (comp.domain) {
            competitors.push({ domain: comp.domain, position: comp.position ?? 99 });
          }
        }
      }
    }

    let battleStatus: AiCompetitiveLandscape["battleStatus"] = "neither";
    if (c.brandCited && competitors.length > 0) battleStatus = "both_cited";
    else if (c.brandCited) battleStatus = "brand_wins";
    else if (competitors.length > 0) battleStatus = "competitor_wins";

    return {
      keyword: c.keyword,
      brandCited: c.brandCited,
      brandPosition: c.citedPosition,
      competitors,
      battleStatus,
    };
  });
}

export async function generateCompetitorAiSignals(
  brandId: string,
  since: Date,
): Promise<Array<{ type: string; priority: string; message: string; keyword: string }>> {
  const landscape = await getCompetitorAiLandscape(brandId, since);
  const signals: Array<{ type: string; priority: string; message: string; keyword: string }> = [];

  for (const kw of landscape) {
    if (kw.battleStatus === "competitor_wins" && kw.competitors.length > 0) {
      signals.push({
        type: "issue",
        priority: "high",
        message: `${kw.competitors[0].domain} is cited #${kw.competitors[0].position} for "${kw.keyword}" — you are not cited.`,
        keyword: kw.keyword,
      });
    }
    if (kw.battleStatus === "brand_wins") {
      signals.push({
        type: "win",
        priority: "medium",
        message: `You are cited #${kw.brandPosition ?? "?"} for "${kw.keyword}" with no competitor citations.`,
        keyword: kw.keyword,
      });
    }
  }

  return signals;
}
