/**
 * Analytics Dashboard Server Component
 *
 * Server-side wrapper that pre-fetches analytics data before rendering client component.
 * This eliminates the need for client-side API calls to fetch initial data.
 *
 * Pattern Reference: This follows the same server/client split as
 * app/[lang]/dashboard/components/BillingPanelServer.tsx
 */

import { prisma } from "@/lib/db";
import { requireStaffAuth } from "@/lib/staff-auth";
import AnalyticsDashboardClient from "./AnalyticsDashboardClient";
import type { AnalyticsData } from "./AnalyticsDashboardClient";

/**
 * Fetch analytics data server-side.
 * This is the same logic as the API route, but runs server-side.
 */
async function fetchAnalyticsData(
  timeRange: string,
): Promise<AnalyticsData | null> {
  try {
    const now = new Date();
    const start = new Date();

    switch (timeRange) {
      case "today":
        start.setHours(0, 0, 0, 0);
        break;
      case "week":
        start.setDate(now.getDate() - 7);
        break;
      case "month":
        start.setMonth(now.getMonth() - 1);
        break;
    }

    // Fetch from Prisma (Primary Source)
    const [
      pTotalVisits,
      pUniqueVisitors,
      pDemos,
      pSignups,
      pTopPages,
      pVisitsByCountry,
      pVisitsByDevice,
    ] = await Promise.all([
      prisma.user_sessions.count({
        where: { createdAt: { gte: start } },
      }),
      prisma.user_sessions.groupBy({
        by: ["userId"],
        where: { createdAt: { gte: start } },
      }),
      prisma.demo_bookings.count({
        where: { createdAt: { gte: start } },
      }),
      prisma.users.count({
        where: {
          role: "CUSTOMER",
          createdAt: { gte: start },
        },
      }),
      prisma.site_visits.groupBy({
        by: ["page"],
        where: { createdAt: { gte: start } },
        _count: { page: true },
        orderBy: { _count: { page: "desc" } },
        take: 10,
      }),
      prisma.user_sessions.groupBy({
        by: ["country"],
        where: {
          createdAt: { gte: start },
          country: { not: null },
        },
        _count: { country: true },
        orderBy: { _count: { country: "desc" } },
      }),
      prisma.user_sessions.groupBy({
        by: ["deviceType"],
        where: { createdAt: { gte: start } },
        _count: { deviceType: true },
      }),
    ]);

    // Aggregate data from Convex (via Prisma adapter)
    const totalVisits = pTotalVisits;
    const unique = pUniqueVisitors.length;
    const demos = pDemos;
    const signups = pSignups;

    // Conversions
    const visitorToDemo =
      unique > 0 ? parseFloat(((demos / unique) * 100).toFixed(1)) : 0;
    const visitorToSignup =
      unique > 0 ? parseFloat(((signups / unique) * 100).toFixed(1)) : 0;
    const demoToSignup =
      demos > 0 ? parseFloat(((signups / demos) * 100).toFixed(1)) : 0;

    // Top pages
    const topPages = pTopPages.map((p) => ({
      page: p.page,
      visits: p._count.page,
    }));

    // By country
    const byCountry: Record<string, number> = {};
    pVisitsByCountry.forEach((v) => {
      if (v.country) {
        byCountry[v.country] = v._count.country;
      }
    });

    // By device
    const byDevice: Record<string, number> = {
      Desktop: 0,
      Mobile: 0,
      Tablet: 0,
    };
    pVisitsByDevice.forEach((v) => {
      const type =
        v.deviceType.charAt(0).toUpperCase() +
        v.deviceType.slice(1).toLowerCase();
      byDevice[type] = (byDevice[type] || 0) + v._count.deviceType;
    });

    return {
      visits: {
        total: totalVisits,
        unique,
        today: 0,
        week: timeRange === "week" ? totalVisits : 0,
        month: timeRange === "month" ? totalVisits : 0,
      },
      conversions: {
        visitorToDemo,
        visitorToSignup,
        demoToSignup,
      },
      topPages,
      byCountry,
      byDevice,
    };
  } catch (error) {
    console.error("Failed to fetch analytics:", error);
    return null;
  }
}

/**
 * Server Component: Fetches analytics data server-side and passes to client.
 *
 * Benefits:
 * - Eliminates waterfall of client-side fetches
 * - Better security (no exposed API endpoints for initial data)
 * - Faster initial render (data available immediately)
 */
export default async function AnalyticsDashboard() {
  // Server-side: Validate staff auth and fetch analytics
  const user = await requireStaffAuth();

  // Default to 'week' time range for initial load
  const initialTimeRange = "week";
  const initialAnalytics = await fetchAnalyticsData(initialTimeRange);

  return (
    <AnalyticsDashboardClient
      initialAnalytics={initialAnalytics}
      initialTimeRange={initialTimeRange}
      user={{ id: user.id, role: user.role }}
    />
  );
}
