/**
 * GET /api/ai-roi?brandId=…&range=90d
 *
 * Returns the AI ROI dashboard data — revenue by channel, funnel
 * metrics, top pages by revenue, monthly trends, and cost analysis.
 */

import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";

export const dynamic = "force-dynamic";

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

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

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

  const range = url.searchParams.get("range") ?? "90d";
  const days = parseInt(range) || 90;
  const since = new Date(Date.now() - days * 86_400_000);
  const prevSince = new Date(since.getTime() - days * 86_400_000);

  const [
    totalRevenue,
    totalConversions,
    prevConversions,
    prevRevenue,
    byChannel,
    citationCount,
    engaged,
    qualifiedLeads,
    topPages,
    monthlyTrend,
    multiTouch,
  ] = await Promise.all([
    prisma.aiAttribution.aggregate({
      where: { brandId, timestamp: { gte: since }, dealValue: { gt: 0 }, dealStatus: "closed_won" },
      _sum: { dealValue: true },
    }).catch(() => ({ _sum: { dealValue: null } })),

    prisma.aiAttribution.count({
      where: { brandId, timestamp: { gte: since }, converted: true },
    }).catch(() => 0),

    prisma.aiAttribution.count({
      where: { brandId, timestamp: { gte: prevSince, lt: since }, converted: true },
    }).catch(() => 0),

    prisma.aiAttribution.aggregate({
      where: { brandId, timestamp: { gte: prevSince, lt: since }, dealValue: { gt: 0 }, dealStatus: "closed_won" },
      _sum: { dealValue: true },
    }).catch(() => ({ _sum: { dealValue: null } })),

    prisma.aiAttribution.groupBy({
      by: ["channel"],
      where: { brandId, timestamp: { gte: since }, dealValue: { gt: 0 }, dealStatus: "closed_won" },
      _sum: { dealValue: true },
      _count: true,
    }).catch(() => []),

    prisma.aiCitation.count({
      where: { brandId, brandCited: true, checkedAt: { gte: since } },
    }).catch(() => 0),

    prisma.aiAttribution.count({
      where: { brandId, timestamp: { gte: since }, engagementScore: { gte: 50 } },
    }).catch(() => 0),

    prisma.aiAttribution.count({
      where: { brandId, timestamp: { gte: since }, converted: true, leadType: { not: null } },
    }).catch(() => 0),

    prisma.aiAttribution.groupBy({
      by: ["landingPage"],
      where: { brandId, timestamp: { gte: since }, converted: true },
      _count: true,
      _sum: { dealValue: true },
      orderBy: { _sum: { dealValue: "desc" } },
      take: 10,
    }).catch(() => []),

    getMonthlyTrend(brandId, 12),

    Promise.all([
      prisma.aiAttribution.count({
        where: { brandId, timestamp: { gte: since }, converted: true, aiPlatform: { not: "behavioral_model" } },
      }).catch(() => 0),
      prisma.aiAttribution.count({
        where: { brandId, timestamp: { gte: since }, converted: true, aiPlatform: "behavioral_model" },
      }).catch(() => 0),
    ]),
  ]);

  const totalReferrals = await prisma.aiAttribution.count({
    where: { brandId, timestamp: { gte: since } },
  }).catch(() => 0);

  const revenue = totalRevenue._sum.dealValue ?? 0;
  const prevRev = prevRevenue._sum.dealValue ?? 0;
  const revenueGrowth = prevRev > 0 ? Math.round(((revenue - prevRev) / prevRev) * 1000) / 10 : 0;
  const conversionGrowth = prevConversions > 0 ? Math.round(((totalConversions - prevConversions) / prevConversions) * 1000) / 10 : 0;

  const planPrice = getPlanPrice(brand.plan, brand.billingCycle);
  const roiMultiplier = planPrice > 0 && revenue > 0 ? Math.round((revenue / planPrice) * 10) / 10 : 0;

  const channelRevenue = byChannel.map((c) => ({
    channel: c.channel,
    revenue: c._sum.dealValue ?? 0,
    conversions: typeof c._count === "number" ? c._count : 0,
  }));

  const assistedRevenue = await prisma.aiAttribution.aggregate({
    where: { brandId, timestamp: { gte: since }, dealValue: { gt: 0 }, dealStatus: "closed_won", aiPlatform: "behavioral_model" },
    _sum: { dealValue: true },
  }).catch(() => ({ _sum: { dealValue: null } }));

  const engagementRate = totalReferrals > 0 ? Math.round((engaged / totalReferrals) * 1000) / 10 : 0;
  const qualificationRate = totalConversions > 0 ? Math.round((qualifiedLeads / totalConversions) * 1000) / 10 : 0;

  return NextResponse.json({
    headline: {
      totalRevenue: revenue,
      totalConversions,
      roiMultiplier,
      revenueGrowth,
      conversionGrowth,
    },
    channelRevenue: [
      ...channelRevenue,
      {
        channel: "assisted",
        revenue: assistedRevenue._sum.dealValue ?? 0,
        conversions: multiTouch[1],
      },
    ],
    funnel: {
      citationsDetected: citationCount,
      referralClicks: totalReferrals,
      engagedVisitors: engaged,
      engagementRate,
      conversions: totalConversions,
      qualifiedLeads,
      qualificationRate,
      closedRevenue: revenue,
    },
    monthlyTrend,
    topPages: topPages.map((p) => ({
      page: p.landingPage,
      conversions: typeof p._count === "number" ? p._count : 0,
      revenue: p._sum.dealValue ?? 0,
    })),
    costAnalysis: {
      subscriptionCost: planPrice,
      aiCreditsUsed: brand.aiCreditsUsed,
      totalInvestment: planPrice,
      totalRevenue: revenue,
      roi: roiMultiplier,
      paybackDays: planPrice > 0 && revenue > 0 ? Math.round((planPrice / revenue) * days) : null,
    },
    range,
    days,
  });
}

// ─── Helpers ───────────────────────────────────────────────────────────────

async function getMonthlyTrend(brandId: string, months: number) {
  const since = new Date();
  since.setMonth(since.getMonth() - months);

  const attributions = await prisma.aiAttribution.findMany({
    where: { brandId, timestamp: { gte: since } },
    select: { timestamp: true, converted: true, channel: true, dealValue: true, dealStatus: true },
    orderBy: { timestamp: "asc" },
  });

  const buckets = new Map<string, {
    month: string;
    totalRevenue: number;
    llmoRevenue: number;
    geoRevenue: number;
    aeoRevenue: number;
    conversions: number;
    referrals: number;
  }>();

  for (const a of attributions) {
    const month = `${a.timestamp.getFullYear()}-${String(a.timestamp.getMonth() + 1).padStart(2, "0")}`;
    const bucket = buckets.get(month) ?? {
      month,
      totalRevenue: 0,
      llmoRevenue: 0,
      geoRevenue: 0,
      aeoRevenue: 0,
      conversions: 0,
      referrals: 0,
    };

    bucket.referrals++;
    if (a.converted) bucket.conversions++;

    const rev = a.dealStatus === "closed_won" && a.dealValue ? a.dealValue : 0;
    bucket.totalRevenue += rev;
    if (a.channel === "llmo") bucket.llmoRevenue += rev;
    else if (a.channel === "geo") bucket.geoRevenue += rev;
    else if (a.channel === "aeo") bucket.aeoRevenue += rev;

    buckets.set(month, bucket);
  }

  return [...buckets.values()].sort((a, b) => a.month.localeCompare(b.month));
}

function getPlanPrice(plan: string, billingCycle: string): number {
  const prices: Record<string, [number, number]> = {
    growth: [299, 249],
    professional: [499, 416],
    agency: [1499, 1249],
    agency_pro: [3499, 2916],
    trial: [0, 0],
    enterprise: [0, 0],
  };
  const [monthly, annual] = prices[plan] ?? [0, 0];
  return billingCycle === "annual" ? annual : monthly;
}
