/**
 * GET /api/pages/[pageId]/compare?range=30d|60d|90d&vs=previous|yearAgo
 *
 * Compares the page's PageDailyMetric data across two periods and
 * returns per-metric deltas for the Launch Tracker detail panel.
 */

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, { params }: { params: { pageId: string } }) {
  const user = await getCurrentUser();
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const { searchParams } = new URL(req.url);
  const rangeStr = searchParams.get("range") || "30d";
  const vs = searchParams.get("vs") === "yearAgo" ? "yearAgo" : "previous";
  const days = rangeStr === "7d" ? 7 : rangeStr === "60d" ? 60 : rangeStr === "90d" ? 90 : 30;

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

  const now = new Date();
  const currentEnd = now;
  const currentStart = new Date(now.getTime() - days * 24 * 60 * 60 * 1000);

  let prevStart: Date, prevEnd: Date;
  if (vs === "yearAgo") {
    prevEnd = new Date(currentEnd); prevEnd.setFullYear(prevEnd.getFullYear() - 1);
    prevStart = new Date(currentStart); prevStart.setFullYear(prevStart.getFullYear() - 1);
  } else {
    prevEnd = new Date(currentStart);
    prevStart = new Date(currentStart.getTime() - days * 24 * 60 * 60 * 1000);
  }

  const [current, previous] = await Promise.all([
    aggregate(page.id, currentStart, currentEnd),
    aggregate(page.id, prevStart, prevEnd),
  ]);

  return NextResponse.json({
    range: rangeStr,
    vs,
    current: { ...current, start: currentStart, end: currentEnd },
    previous: { ...previous, start: prevStart, end: prevEnd },
    deltas: {
      clicks: delta(current.clicks, previous.clicks),
      impressions: delta(current.impressions, previous.impressions),
      ctr: delta(current.ctr, previous.ctr),
      // Position: lower is better, so invert the delta sign semantically on the UI side
      avgPosition: delta(current.avgPosition, previous.avgPosition),
    },
  });
}

async function aggregate(pageId: string, start: Date, end: Date) {
  const rows = await prisma.pageDailyMetric.findMany({
    where: { pageId, date: { gte: start, lte: end } },
    select: { clicks: true, impressions: true, ctr: true, avgPosition: true },
  });
  if (rows.length === 0) {
    return { clicks: 0, impressions: 0, ctr: 0, avgPosition: 0, days: 0 };
  }
  const clicks = rows.reduce((s, r) => s + r.clicks, 0);
  const impressions = rows.reduce((s, r) => s + r.impressions, 0);
  const ctr = impressions > 0 ? (clicks / impressions) * 100 : 0;
  const avgPosition = rows.reduce((s, r) => s + r.avgPosition, 0) / rows.length;
  return { clicks, impressions, ctr, avgPosition, days: rows.length };
}

function delta(current: number, previous: number) {
  const absolute = current - previous;
  const relative = previous === 0 ? (current > 0 ? 100 : 0) : (absolute / previous) * 100;
  return { absolute, relative };
}
