/**
 * GET /api/pages/[pageId]/history
 *
 * Full lifecycle history for a single PageRecord:
 *   - all status changes (timeline)
 *   - daily metrics (clicks, impressions, CTR, position over time)
 *   - redirects pointing TO this page
 *   - redirects FROM this page
 *   - synthesized event timeline combining the above
 */

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 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 [statusHistory, dailyMetrics, redirectsIn, redirectsOut] = await Promise.all([
    prisma.pageStatusChange.findMany({
      where: { pageId: page.id },
      orderBy: { detectedAt: "asc" },
    }),
    prisma.pageDailyMetric.findMany({
      where: { pageId: page.id },
      orderBy: { date: "asc" },
    }),
    prisma.redirectRecord.findMany({
      where: { brandId: page.brandId, targetPageId: page.id, isActive: true },
      orderBy: { firstSeenAt: "desc" },
    }),
    prisma.redirectRecord.findMany({
      where: { brandId: page.brandId, sourcePageId: page.id, isActive: true },
      orderBy: { firstSeenAt: "desc" },
    }),
  ]);

  // Build a unified timeline of lifecycle events
  type TimelineEvent = {
    at: Date;
    type: "first_seen" | "added_to_nav" | "removed_from_nav" | "status_change" | "redirect_in" | "redirect_out" | "traffic_milestone";
    label: string;
    status?: number;
  };
  const timeline: TimelineEvent[] = [];
  timeline.push({ at: page.firstSeenAt, type: "first_seen", label: "First detected on site", status: 200 });
  if (page.addedToNavAt) {
    timeline.push({ at: page.addedToNavAt, type: "added_to_nav", label: "Added to main navigation" });
  }
  if (page.removedFromNavAt) {
    timeline.push({ at: page.removedFromNavAt, type: "removed_from_nav", label: "Removed from main navigation" });
  }
  statusHistory.forEach((c) => {
    timeline.push({
      at: c.detectedAt,
      type: "status_change",
      label: `Status changed from ${c.fromStatus} → ${c.toStatus}`,
      status: c.toStatus,
    });
  });
  redirectsIn.forEach((r) => {
    timeline.push({
      at: r.firstSeenAt,
      type: "redirect_in",
      label: `${r.sourceUrl} → ${r.targetUrl} (${r.statusCode})`,
    });
  });
  redirectsOut.forEach((r) => {
    timeline.push({
      at: r.firstSeenAt,
      type: "redirect_out",
      label: `This page redirects to ${r.targetUrl} (${r.statusCode})`,
    });
  });
  // Simple traffic milestones: the first day clicks crossed 100, 1000, 10000
  const milestones = [100, 1000, 10000];
  let runningClicks = 0;
  for (const m of dailyMetrics) {
    const before = runningClicks;
    runningClicks += m.clicks;
    for (const threshold of milestones) {
      if (before < threshold && runningClicks >= threshold) {
        timeline.push({
          at: m.date,
          type: "traffic_milestone",
          label: `Crossed ${threshold.toLocaleString()} total clicks`,
        });
      }
    }
  }
  timeline.sort((a, b) => a.at.getTime() - b.at.getTime());

  return NextResponse.json({
    page: {
      id: page.id,
      url: page.url,
      fullUrl: page.fullUrl,
      title: page.title,
      currentStatus: page.currentStatus,
      firstSeenAt: page.firstSeenAt,
      lastSeenAt: page.lastSeenAt,
      isInNav: page.isInNav,
      addedToNavAt: page.addedToNavAt,
      totalClicks: page.totalClicks,
      totalImpressions: page.totalImpressions,
      currentCtr: page.currentCtr,
      currentPosition: page.currentPosition,
      totalVisits: page.totalVisits,
      metaDescription: page.metaDescription,
      h1: page.h1,
      canonicalUrl: page.canonicalUrl,
      wordCount: page.wordCount,
      daysLive: Math.max(0, Math.floor((Date.now() - page.firstSeenAt.getTime()) / (1000 * 60 * 60 * 24))),
    },
    statusHistory,
    dailyMetrics: dailyMetrics.map((m) => ({
      date: m.date,
      clicks: m.clicks,
      impressions: m.impressions,
      ctr: m.ctr,
      avgPosition: m.avgPosition,
      sessions: m.sessions,
      conversions: m.conversions,
      statusCode: m.statusCode,
    })),
    redirectsIn: redirectsIn.map((r) => ({
      id: r.id, sourceUrl: r.sourceUrl, targetUrl: r.targetUrl,
      statusCode: r.statusCode, firstSeenAt: r.firstSeenAt,
    })),
    redirectsOut: redirectsOut.map((r) => ({
      id: r.id, sourceUrl: r.sourceUrl, targetUrl: r.targetUrl,
      statusCode: r.statusCode, firstSeenAt: r.firstSeenAt,
    })),
    timeline,
  });
}
