import { NextResponse } from "next/server";
import { sendAlert } from "@/lib/alert";

/**
 * Visitor summary cron — polls the self-hosted Umami API and posts a digest to
 * Telegram. Umami has no native webhook, so we authenticate and read its REST API.
 *
 *   POST/GET /api/cron/visitor-summary            (header: x-cron-secret)
 *   GET      /api/cron/visitor-summary?hours=24    — window (default 24, max 168)
 *
 * Env:
 *   UMAMI_BASE_URL    (default https://analytics.manohargupta.com)
 *   UMAMI_USERNAME    Umami login (admin or a read-only user)
 *   UMAMI_PASSWORD
 *   UMAMI_WEBSITE_ID  (default the Tia website id)
 *
 * Recommended schedule: once a day. Set hours=24 for a daily digest, or call it
 * more often (e.g. hours=1 hourly) if you want tighter pulse during launch.
 */
export const dynamic = "force-dynamic";

const UMAMI_BASE = process.env.UMAMI_BASE_URL || "https://analytics.manohargupta.com";
const WEBSITE_ID = process.env.UMAMI_WEBSITE_ID || "79444c19-ee31-4fab-baf5-f4e61098eeba";

function authed(request: Request): boolean {
  return request.headers.get("x-cron-secret") === process.env.CRON_SECRET;
}

export async function POST(request: Request) {
  if (!authed(request)) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  return runSummary(request);
}

export async function GET(request: Request) {
  if (!authed(request)) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  return runSummary(request);
}

/** Authenticate with Umami and return a Bearer token, or null on failure. */
async function umamiLogin(): Promise<string | null> {
  try {
    const res = await fetch(`${UMAMI_BASE}/api/auth/login`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        username: process.env.UMAMI_USERNAME,
        password: process.env.UMAMI_PASSWORD,
      }),
    });
    if (!res.ok) {
      console.error("umamiLogin failed:", res.status, await res.text().catch(() => ""));
      return null;
    }
    const data = await res.json();
    return data?.token || null;
  } catch (e) {
    console.error("umamiLogin error:", e);
    return null;
  }
}

// Umami wraps metric values as { value, prev }; tolerate both shapes + raw numbers.
const num = (v: unknown): number => {
  if (typeof v === "number") return v;
  if (v && typeof v === "object" && "value" in v) return Number((v as { value: unknown }).value) || 0;
  return Number(v) || 0;
};

async function runSummary(request: Request) {
  const { searchParams } = new URL(request.url);
  const hours = Math.max(1, Math.min(168, Number(searchParams.get("hours")) || 24));
  const endAt = Date.now();
  const startAt = endAt - hours * 3_600_000;

  if (!process.env.UMAMI_USERNAME || !process.env.UMAMI_PASSWORD) {
    return NextResponse.json({ error: "UMAMI_USERNAME / UMAMI_PASSWORD not set" }, { status: 500 });
  }

  const token = await umamiLogin();
  if (!token) {
    await sendAlert("warn", "Visitor summary unavailable", "Could not authenticate with Umami", { silent: true });
    return NextResponse.json({ error: "umami auth failed" }, { status: 502 });
  }

  const headers = { Authorization: `Bearer ${token}` };
  const qs = `startAt=${startAt}&endAt=${endAt}`;

  // Stats
  let stats: Record<string, unknown> = {};
  try {
    const r = await fetch(`${UMAMI_BASE}/api/websites/${WEBSITE_ID}/stats?${qs}`, { headers });
    stats = await r.json();
  } catch (e) {
    console.error("umami stats error:", e);
  }

  // Top pages
  let topPages: Array<{ x?: string; url?: string; y?: number; value?: number }> = [];
  try {
    const r = await fetch(`${UMAMI_BASE}/api/websites/${WEBSITE_ID}/metrics?type=url&${qs}&limit=5`, { headers });
    const j = await r.json();
    if (Array.isArray(j)) topPages = j;
  } catch (e) {
    console.error("umami metrics error:", e);
  }

  // Active right now
  let active = 0;
  try {
    const r = await fetch(`${UMAMI_BASE}/api/websites/${WEBSITE_ID}/active`, { headers });
    const a = await r.json();
    active = typeof a === "number" ? a : num((a as { visitors?: unknown; x?: unknown })?.visitors ?? (a as { x?: unknown })?.x);
  } catch (e) {
    console.error("umami active error:", e);
  }

  const pageviews = num(stats.pageviews);
  const visitors = num(stats.visitors);
  const visits = num(stats.visits);
  const bounces = num(stats.bounces);
  const totaltime = num(stats.totaltime);

  const bounceRate = visits ? Math.round((bounces / visits) * 100) : 0;
  const avgVisit = visits ? Math.round(totaltime / visits) : 0; // seconds

  const pagesText =
    topPages
      .slice(0, 5)
      .map(p => `• ${p.x || p.url || "?"} — ${p.y ?? p.value ?? 0}`)
      .join("\n") || "—";

  const label = hours === 24 ? "Last 24h" : `Last ${hours}h`;
  const body = [
    `👥 Visitors: ${visitors}`,
    `🔁 Visits: ${visits}`,
    `📄 Page views: ${pageviews}`,
    `↩️ Bounce rate: ${bounceRate}%`,
    `⏱ Avg visit: ${avgVisit}s`,
    `🟢 Active now: ${active}`,
    ``,
    `Top pages:`,
    pagesText,
  ].join("\n");

  const delivered = await sendAlert("info", `📊 Visitor summary — ${label}`, body, { silent: true });

  return NextResponse.json({
    ok: true,
    delivered,
    summary: { visitors, visits, pageviews, bounceRate, avgVisit, active },
  });
}
