/**
 * GET /api/admin/debug/verify-events
 *
 * Read-only diagnostic for Site Tag Analytics figures (form_start,
 * click_to_call). Verifies the headline numbers against TrackedEvent
 * + SiteEvent and ships sample rows + per-day breakdowns + per-page
 * distribution so we can tell whether the counts look real or
 * duplicated.
 *
 * Lives under /api/admin/* (not /api/debug/*) so middleware on
 * admin.meseoapp.com lets it through. The host rewrites every non-
 * passthrough path to /admin/<x>, which 404'd the original
 * /api/debug/verify-events location; /api/admin is in the passthrough
 * set AND triggers the edge superadmin gate.
 *
 * Usage:
 *   GET /api/admin/debug/verify-events?brandId=<id>[&siteId=<id>][&days=30]
 *
 * brandId is required — no hardcoded defaults. Passing a bare URL
 * used to return data for Modern Heart and Vascular, which is both
 * footgun (accidentally probing the wrong brand) and misleading
 * on a multi-tenant platform. Callers MUST pass an explicit brandId;
 * siteId is resolved from the brand's TrackedSite when omitted.
 *
 * Notes baked into the response so the curl-er sees them inline:
 *   - t.js form_start  : DEDUPED per (form, page-load) via
 *                         trackedFormStarts[formKey]. NOT deduped
 *                         across page navigations or sessions.
 *   - t.js click_to_call: NOT deduped. Every tap on a tel: link
 *                          fires a fresh event.
 *
 * Superadmin-only.
 */

import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { requireSuperadmin, withAdminTiming } from "@/lib/admin-auth";

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

export async function GET(req: Request) {
  const denied = await requireSuperadmin();
  if (denied) return denied;

  const { searchParams } = new URL(req.url);
  const brandId = searchParams.get("brandId");
  if (!brandId) {
    return NextResponse.json(
      { error: "brandId query param required. Usage: ?brandId=<id>[&siteId=<id>][&days=30]" },
      { status: 400 },
    );
  }
  // Resolve siteId from the brand's TrackedSite when the caller
  // doesn't pass one explicitly. Keeping the explicit override for
  // cases where multiple TrackedSites exist for one brand (edge-case
  // but historically possible on legacy rows).
  let trackedSiteId = searchParams.get("siteId");
  if (!trackedSiteId) {
    const site = await prisma.trackedSite.findUnique({
      where: { brandId },
      select: { id: true },
    });
    if (!site) {
      return NextResponse.json(
        { error: "No TrackedSite found for brandId. Pass siteId explicitly or verify the brand has a Site Tag installed." },
        { status: 404 },
      );
    }
    trackedSiteId = site.id;
  }
  const days  = Math.max(1, Math.min(90, Number(searchParams.get("days") ?? 30)));
  const since = new Date(Date.now() - days * 86_400_000);

  return NextResponse.json(await withAdminTiming("debug.verify-events", async () => {
    // ── Headline counts (TrackedEvent + SiteEvent) ────────────────
    const [
      formStartsTE, clickToCallsTE, formStartsSE, clickToCallsSE,
      formSubmitsTE, totalEventsTE,
    ] = await Promise.all([
      prisma.trackedEvent.count({ where: { trackedSiteId, eventType: "form_start", timestamp: { gte: since } } }),
      prisma.trackedEvent.count({ where: { trackedSiteId, eventType: "click_to_call", timestamp: { gte: since } } }),
      prisma.siteEvent.count({ where: { brandId, eventType: "form_start", timestamp: { gte: since } } }),
      prisma.siteEvent.count({ where: { brandId, eventType: "click_to_call", timestamp: { gte: since } } }),
      prisma.trackedEvent.count({ where: { trackedSiteId, eventType: "form_submit", timestamp: { gte: since } } }),
      prisma.trackedEvent.count({ where: { trackedSiteId, timestamp: { gte: since } } }),
    ]);

    console.info("[VERIFY] form_start TrackedEvent:", formStartsTE);
    console.info("[VERIFY] click_to_call TrackedEvent:", clickToCallsTE);
    console.info("[VERIFY] form_start SiteEvent:", formStartsSE);
    console.info("[VERIFY] click_to_call SiteEvent:", clickToCallsSE);

    // ── Sample rows so we can eyeball what's being captured ──────
    const [formSamples, callSamples] = await Promise.all([
      prisma.trackedEvent.findMany({
        where: { trackedSiteId, eventType: "form_start", timestamp: { gte: since } },
        orderBy: { timestamp: "desc" },
        take: 10,
        select: { id: true, timestamp: true, pageUrl: true, sessionId: true, metadata: true },
      }),
      prisma.trackedEvent.findMany({
        where: { trackedSiteId, eventType: "click_to_call", timestamp: { gte: since } },
        orderBy: { timestamp: "desc" },
        take: 10,
        select: { id: true, timestamp: true, pageUrl: true, sessionId: true, metadata: true },
      }),
    ]);

    console.info("[VERIFY] form_start samples:", JSON.stringify(formSamples, null, 2));
    console.info("[VERIFY] click_to_call samples:", JSON.stringify(callSamples, null, 2));

    // ── Per-day buckets so a spike day is visible ────────────────
    // Cheap: pull the timestamps + bucket client-side.
    const [allFormStarts, allCalls] = await Promise.all([
      prisma.trackedEvent.findMany({
        where: { trackedSiteId, eventType: "form_start", timestamp: { gte: since } },
        select: { timestamp: true },
      }),
      prisma.trackedEvent.findMany({
        where: { trackedSiteId, eventType: "click_to_call", timestamp: { gte: since } },
        select: { timestamp: true },
      }),
    ]);
    const bucket = (rows: Array<{ timestamp: Date }>): Array<{ date: string; count: number }> => {
      const map = new Map<string, number>();
      for (const r of rows) {
        const key = r.timestamp.toISOString().slice(0, 10);
        map.set(key, (map.get(key) ?? 0) + 1);
      }
      return Array.from(map.entries()).sort((a, b) => a[0].localeCompare(b[0])).map(([date, count]) => ({ date, count }));
    };

    // ── Per-page distribution — answers "are clicks coming from
    // one page or spread across the site?" Critical for spotting
    // a button that fires on every load (pseudo-event spam). ──
    const [formByPage, callByPage] = await Promise.all([
      prisma.trackedEvent.groupBy({
        by: ["pageUrl"],
        where: { trackedSiteId, eventType: "form_start", timestamp: { gte: since } },
        _count: true,
        orderBy: { _count: { pageUrl: "desc" } },
        take: 10,
      }),
      prisma.trackedEvent.groupBy({
        by: ["pageUrl"],
        where: { trackedSiteId, eventType: "click_to_call", timestamp: { gte: since } },
        _count: true,
        orderBy: { _count: { pageUrl: "desc" } },
        take: 10,
      }),
    ]);

    // ── Per-session distribution — surfaces a single user
    // hammering the call button (would inflate the count). ──
    const [formBySession, callBySession] = await Promise.all([
      prisma.trackedEvent.groupBy({
        by: ["sessionId"],
        where: { trackedSiteId, eventType: "form_start", timestamp: { gte: since } },
        _count: true,
        orderBy: { _count: { sessionId: "desc" } },
        take: 5,
      }),
      prisma.trackedEvent.groupBy({
        by: ["sessionId"],
        where: { trackedSiteId, eventType: "click_to_call", timestamp: { gte: since } },
        _count: true,
        orderBy: { _count: { sessionId: "desc" } },
        take: 5,
      }),
    ]);

    return {
      scope: {
        trackedSiteId,
        brandId,
        windowDays: days,
        sinceISO: since.toISOString(),
      },
      counts: {
        formStarts:    { trackedEvent: formStartsTE,    siteEvent: formStartsSE,    delta: formStartsTE - formStartsSE },
        clickToCalls:  { trackedEvent: clickToCallsTE,  siteEvent: clickToCallsSE,  delta: clickToCallsTE - clickToCallsSE },
        formSubmits:   { trackedEvent: formSubmitsTE },
        totalEvents:   { trackedEvent: totalEventsTE },
      },
      perDay: {
        formStarts: bucket(allFormStarts),
        clickToCalls: bucket(allCalls),
      },
      perPage: {
        formStarts: formByPage.map((r) => ({ pageUrl: r.pageUrl, count: r._count })),
        clickToCalls: callByPage.map((r) => ({ pageUrl: r.pageUrl, count: r._count })),
      },
      perSession: {
        // Reading: a sessionId with count > 1 in either bucket =
        // either a real user who repeated the action or a dedup
        // bug. Click-to-call deliberately is NOT deduped, so > 1
        // is expected; form_start IS deduped per form-per-page-load
        // — > 1 here means the same user navigated to the page
        // multiple times and started a form each time, OR there
        // are multiple distinct forms on a page.
        formStartsTopSessions: formBySession.map((r) => ({ sessionId: r.sessionId, count: r._count })),
        clickToCallsTopSessions: callBySession.map((r) => ({ sessionId: r.sessionId, count: r._count })),
      },
      samples: {
        formStarts: formSamples.map((s) => ({ ...s, timestamp: s.timestamp.toISOString() })),
        clickToCalls: callSamples.map((s) => ({ ...s, timestamp: s.timestamp.toISOString() })),
      },
      analyticsQueryShape: {
        // What the Site Tag Analytics dashboard runs against this
        // brand. Read /api/site-tag/analytics for the full path.
        formStart:    `prisma.trackedEvent.count({ where: { trackedSiteId, eventType: "form_start", timestamp: { gte: since } } })`,
        clickToCall:  `prisma.trackedEvent.count({ where: { trackedSiteId, eventType: "click_to_call", timestamp: { gte: since } } })`,
        sameAsHere:   true,
      },
      tagDetectionNotes: {
        formStart: {
          trigger: "focusin event on any field whose .form is present (public/t.js:521-538)",
          dedup: "trackedFormStarts[formKey] — dedupes per form per PAGE LOAD. NOT per session. A page reload OR a navigation back to the same page fires another form_start.",
          formKey: "form.id || form.action || `form-${index in document.forms}`",
          metadata: "{ form_id, form_action, field_name (first focused field) }",
        },
        clickToCall: {
          trigger: "click anywhere that resolves to an <a href=\"tel:...\"> (public/t.js:430-449), capture-phase listener so it fires before navigation",
          dedup: "NONE. Every tap on a tel: link fires a fresh event. A user who taps the phone number 5 times = 5 click_to_call events.",
          metadata: "{ phone_number, link_text, link_url }",
        },
      },
      reasonablenessCheck: {
        // 5 days of data per the prompt → daily averages.
        // Rule of thumb noted in the brief — still reproduced in the
        // response so the curl-er sees the math without re-deriving.
        observedFormStartsPerDay: formStartsTE / Math.max(1, days),
        observedClickToCallPerDay: clickToCallsTE / Math.max(1, days),
        formAbandonRate: formStartsTE > 0
          ? Math.round((1 - formSubmitsTE / formStartsTE) * 1000) / 10
          : null,
      },
    };
  }));
}
