/**
 * Analytics Tracker
 *
 * Privacy-friendly site visit tracking for staff dashboard
 */

import { prisma } from "./db";
import { headers } from "next/headers";

/**
 * Track page visit (call from page components)
 */
export async function trackPageVisit(page: string, userId?: string) {
  try {
    const headersList = await headers();
    const userAgent = headersList.get("user-agent") || "";
    const forwarded = headersList.get("x-forwarded-for");
    const ip = forwarded ? forwarded.split(",")[0] : "";

    // Generate visitor ID from IP (privacy-friendly - no cookies needed)
    const visitorId = await hashVisitorId(ip, userAgent);

    // Generate session ID (valid for 30 minutes)
    const sessionId = await generateSessionId(visitorId);

    // Extract country from IP (simplified - in production use GeoIP service)
    const country = await getCountryFromIp(ip);

    await prisma.siteVisit.create({
      data: {
        visitorId,
        sessionId,
        page,
        country,
        userAgent: userAgent.substring(0, 255),
        referrer: headersList.get("referer") || null,
        userId,
      },
    });
  } catch (error) {
    // Silent fail - don't break page rendering if tracking fails
    console.error("Failed to track page visit:", error);
  }
}

/**
 * Hash visitor ID for privacy
 */
async function hashVisitorId(ip: string, userAgent: string): Promise<string> {
  const data = `${ip}:${userAgent}`;
  const encoder = new TextEncoder();
  const dataBuffer = encoder.encode(data);
  const hashBuffer = await crypto.subtle.digest("SHA-256", dataBuffer);
  const hashArray = Array.from(new Uint8Array(hashBuffer));
  return hashArray
    .map((b) => b.toString(16).padStart(2, "0"))
    .join("")
    .substring(0, 32);
}

/**
 * Generate session ID (valid for 30 minutes)
 */
async function generateSessionId(visitorId: string): Promise<string> {
  const now = Date.now();
  const sessionWindow = 30 * 60 * 1000; // 30 minutes
  const sessionBucket = Math.floor(now / sessionWindow);

  const data = `${visitorId}:${sessionBucket}`;
  const encoder = new TextEncoder();
  const dataBuffer = encoder.encode(data);
  const hashBuffer = await crypto.subtle.digest("SHA-256", dataBuffer);
  const hashArray = Array.from(new Uint8Array(hashBuffer));
  return hashArray
    .map((b) => b.toString(16).padStart(2, "0"))
    .join("")
    .substring(0, 32);
}

/**
 * Get country from IP address (simplified - use GeoIP service in production)
 */
async function getCountryFromIp(ip: string): Promise<string | null> {
  // For development, return null
  // In production, integrate with a GeoIP service like:
  // - MaxMind GeoIP2
  // - IP-API.com
  // - ipinfo.io

  // Example:
  // const response = await fetch(`https://ipapi.co/${ip}/country_name/`);
  // return await response.text();

  return null;
}

/**
 * Get analytics summary (for API routes)
 */
export async function getAnalyticsSummary(days: number = 7) {
  const start = new Date();
  start.setDate(start.getDate() - days);

  const [totalVisits, uniqueVisitors, demos, signups] = await Promise.all([
    prisma.siteVisit.count({
      where: { createdAt: { gte: start } },
    }),
    prisma.siteVisit.groupBy({
      by: ["visitorId"],
      where: { createdAt: { gte: start } },
    }),
    prisma.demo_bookings.count({
      where: { createdAt: { gte: start } },
    }),
    prisma.users.count({
      where: {
        role: "CUSTOMER",
        createdAt: { gte: start },
      },
    }),
  ]);

  const unique = uniqueVisitors.length;

  return {
    totalVisits,
    uniqueVisitors: unique,
    demos,
    signups,
    conversions: {
      visitorToDemo: unique > 0 ? ((demos / unique) * 100).toFixed(1) : "0",
      visitorToSignup: unique > 0 ? ((signups / unique) * 100).toFixed(1) : "0",
      demoToSignup: demos > 0 ? ((signups / demos) * 100).toFixed(1) : "0",
    },
  };
}
