/**
 * GET /api/site-tag/heartbeat?brandId=xxx
 * ----------------------------------------
 * Lightweight poll endpoint for the Site Tag setup page's 30s pollHealth
 * loop. Replaces the 25+ query full /api/site-tag route on every tick
 * with exactly 3 Prisma queries:
 *
 *   1. brand.findUnique + org.memberships  (auth + permission)
 *   2. trackedSite.findUnique              (site status + lastEventAt)
 *   3a. trackedEvent.count(today)          (eventsToday)    } parallel
 *   3b. trackedEvent.count(last 5 min)     (recentEventCount)} parallel
 *
 * The full /api/site-tag route is called once on mount (loadSiteTag) and
 * on manual Refresh. This endpoint is polled every 30s for the three
 * live-updated fields: eventsToday, tag status, lastEventAt.
 *
 * Response shape:
 *   {
 *     installed:        boolean,        // derived: !!lastEventAt || eventsToday > 0
 *     lastEventAt:      string | null,  // ISO timestamp of most recent event
 *     status:           string,         // "active" | "paused" | "disabled"
 *     installedAt:      string | null,  // firstEventAt ISO — first real event
 *     eventsToday:      number,
 *     recentEventCount: number,         // events in last 5 minutes
 *     isHealthy:        boolean,        // active + recent activity
 *   }
 */

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

export const dynamic = "force-dynamic";
export const maxDuration = 10;
// NOTE: runtime = "nodejs" intentionally absent. getCurrentUser() relies on
// Clerk edge-middleware auth header propagation; switching to nodejs runtime
// breaks that and causes 401/403 cascades on every request.

export async function GET(req: Request) {
  try {
    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 });

    // Permission check — exact pattern from /api/site-tag route L49-55
    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 });
    }

    // Q1: TrackedSite lookup (cheap — brandId has a @unique index)
    const trackedSite = await prisma.trackedSite.findUnique({
      where: { brandId },
      select: {
        id: true,
        status: true,
        lastEventAt: true,
        firstEventAt: true,  // schema field; "installedAt" does not exist on TrackedSite
      },
    });

    if (!trackedSite) {
      return NextResponse.json({
        installed: false,
        lastEventAt: null,
        status: "not_installed",
        installedAt: null,
        eventsToday: 0,
        recentEventCount: 0,
        isHealthy: false,
      });
    }

    // Q2 + Q3: parallel counts — both hit the compound (trackedSiteId, timestamp) index
    const startOfToday = new Date();
    startOfToday.setHours(0, 0, 0, 0);
    const fiveMinAgo = new Date(Date.now() - 5 * 60 * 1000);

    const [eventsToday, recentEventCount] = await Promise.all([
      prisma.trackedEvent.count({
        where: { trackedSiteId: trackedSite.id, timestamp: { gte: startOfToday } },
      }),
      prisma.trackedEvent.count({
        where: { trackedSiteId: trackedSite.id, timestamp: { gte: fiveMinAgo } },
      }),
    ]);

    // "installed" is not a TrackedSite column — derive it from observed events
    const installed = !!trackedSite.lastEventAt || eventsToday > 0;

    // "active" is the status value used throughout the codebase (route L172: site.status === "active")
    const isHealthy =
      trackedSite.status === "active" &&
      (recentEventCount > 0 ||
        (trackedSite.lastEventAt !== null &&
          Date.now() - trackedSite.lastEventAt.getTime() < 30 * 60 * 1000));

    return NextResponse.json({
      installed,
      lastEventAt: trackedSite.lastEventAt?.toISOString() ?? null,
      status: trackedSite.status,
      installedAt: trackedSite.firstEventAt?.toISOString() ?? null,
      eventsToday,
      recentEventCount,
      isHealthy,
    });
  } catch (err) {
    console.error("[site-tag/heartbeat] error:", err);
    return NextResponse.json({ error: "Internal error" }, { status: 500 });
  }
}
