/**
 * POST /api/analysis — Run a fresh analysis (never cached).
 * GET /api/analysis?brandId=xxx&range=60 — Latest completed analysis.
 */

import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { runSeasonalAnalysis } from "@/lib/services/analysis-engine";
import { extractActions, type ExtractedAction } from "@/lib/services/analysis-actions";
import { invalidateGscCache } from "@/lib/stores/gsc-cache";

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

export async function POST(req: Request) {
  try {
    const user = await getCurrentUser();
    if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

    const body = await req.json();
    const { brandId, period, prompt, manualCaveats, uploadedNotes, enableResearch, industry } = body;
    if (!brandId || !period?.start || !period?.end) {
      return NextResponse.json({ error: "brandId and period (start, end) required" }, { status: 400 });
    }

    console.log(`[analysis] POST: brandId=${brandId}, period=${period.start} to ${period.end}`);

    const brand = await prisma.brand.findUnique({
      where: { id: brandId },
      include: { organization: { include: { memberships: true } } },
    });
    if (!brand || !brand.organization.memberships.some(m => m.userId === user.id)) {
      return NextResponse.json({ error: "Access denied" }, { status: 403 });
    }

    const job = await prisma.analysisJob.create({
      data: {
        brandId,
        type: "seasonal_performance",
        status: "running",
        prompt: prompt ?? null,
        manualCaveats: manualCaveats ?? [],
        uploadedNotes: uploadedNotes ?? [],
        selectedSources: ["gsc", "ga4", "technical_audit"],
        userId: user.id,
      },
    });

    try {
      const analysis = await runSeasonalAnalysis({ brandId, period, prompt, manualCaveats, uploadedNotes, enableResearch: enableResearch !== false, industry });
      const actions = extractActions(analysis);
      const base = { analysisJobId: analysis.id, clientName: analysis.branding?.clientName ?? "", clientDomain: analysis.branding?.clientDomain ?? "" };
      const extraActions = await extractAiAndSiteTagActions(brandId, period, base);
      const analysisWithActions = { ...analysis, extractedActions: [...actions, ...extraActions] };

      await prisma.analysisJob.update({
        where: { id: job.id },
        data: {
          status: "completed",
          result: JSON.parse(JSON.stringify(analysisWithActions)),
          branding: JSON.parse(JSON.stringify(analysis.branding)),
          completedAt: new Date(),
        },
      });

      console.log(`[analysis] Completed: ${analysis.findings?.length ?? 0} findings, ${analysis.charts?.length ?? 0} charts`);
      invalidateGscCache(brandId); // clear chat cache so next message uses fresh data
      return NextResponse.json(analysisWithActions);
    } catch (err) {
      const msg = err instanceof Error ? err.message : "Analysis failed";
      console.log(`[analysis] Failed: ${msg}`);
      await prisma.analysisJob.update({
        where: { id: job.id },
        data: { status: "failed", errorMessage: msg },
      });
      return NextResponse.json({ error: msg }, { status: 500 });
    }
  } catch (err) {
    const msg = err instanceof Error ? err.message : "Request failed";
    return NextResponse.json({ error: msg }, { status: 500 });
  }
}

/**
 * Generates synthetic Review Actions from AI Attribution + Site Tag behavioral
 * data — signals not present in the main analysis object because they come
 * from tables (AiAttribution, SiteEvent) that the analysis engine doesn't query.
 * Returns an empty array gracefully when neither source has data.
 */
async function extractAiAndSiteTagActions(
  brandId: string,
  period: { start: string; end: string },
  base: Pick<ExtractedAction, "analysisJobId" | "clientName" | "clientDomain">,
): Promise<ExtractedAction[]> {
  const start = new Date(period.start);
  const actions: ExtractedAction[] = [];
  try {
    // AI Attribution — recommend optimising for AI search if traffic exists
    const aiVisits = await prisma.aiAttribution.count({ where: { brandId, timestamp: { gte: start } } }).catch(() => 0);
    if (aiVisits > 0) {
      const platforms = await prisma.aiAttribution.groupBy({
        by: ["aiPlatform"], where: { brandId, timestamp: { gte: start } }, _count: true,
      }).catch(() => [] as Array<{ aiPlatform: string | null; _count: number }>);
      const top = [...platforms].sort((a, b) => (b._count as number) - (a._count as number))[0];
      actions.push({
        id: `action_ai_attribution_${brandId.slice(-6)}`,
        title: `Optimise for AI search citation — ${aiVisits} AI-referred visit${aiVisits === 1 ? "" : "s"} detected`,
        description: `${aiVisits} visit${aiVisits === 1 ? "" : "s"} tracked from AI platforms${top ? ` (top: ${top.aiPlatform || "Unknown"})` : ""}. Expand FAQ-style content and add structured-data schema markup to increase citation frequency in AI-generated answers.`,
        sourceSection: "prediction",
        sourceId: "ai_attribution",
        priority: aiVisits > 50 ? "high" : "medium",
        effort: "medium",
        actionType: "create_content",
        affectedMetric: "AI-referred visits",
        evidence: `${aiVisits} AI-attributed visits recorded in the analysis period.`,
        brandId,
        ...base,
      });
    }

    // Site Tag — rage clicks indicate UX friction reducing conversions
    const rageClicks = await prisma.siteEvent.count({
      where: { brandId, eventType: "rage_click", timestamp: { gte: start } },
    }).catch(() => 0);
    if (rageClicks >= 5) {
      actions.push({
        id: `action_rage_click_${brandId.slice(-6)}`,
        title: `Fix UX friction — ${rageClicks} rage click${rageClicks === 1 ? "" : "s"} detected`,
        description: `${rageClicks} rage-click events recorded by the Site Tag. Rage clicks signal user frustration — common triggers include non-responsive CTAs, slow-loading content, and elements that look interactive but aren't. Review heatmap reports for the top affected pages.`,
        sourceSection: "finding",
        sourceId: "site_tag_rage_click",
        priority: rageClicks > 50 ? "high" : "medium",
        effort: "medium",
        actionType: "investigate",
        affectedMetric: "Rage clicks (UX friction)",
        evidence: `${rageClicks} rage-click events tracked by meSEO Site Tag in the analysis period.`,
        brandId,
        ...base,
      });
    }
  } catch { /* best-effort — never block the main analysis response */ }
  return actions;
}

export async function GET(req: Request) {
  const user = await getCurrentUser();
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const { searchParams } = new URL(req.url);
  const brandId = searchParams.get("brandId");
  if (!brandId) return NextResponse.json({ error: "brandId required" }, { status: 400 });

  const job = await prisma.analysisJob.findFirst({
    where: { brandId, status: "completed" },
    orderBy: { createdAt: "desc" },
  });

  if (!job || !job.result) {
    return NextResponse.json(null);
  }

  return NextResponse.json(job.result);
}
