/**
 * Security Dashboard Server Component
 *
 * Server-side wrapper that pre-fetches security stats 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 { getSecurityStats } from "@/lib/services/security-audit.service";
import { getStaffSession } from "@/lib/staff-session";
import SecurityDashboardClient from "./SecurityDashboardClient";
import type { SecurityStats } from "./SecurityDashboardClient";

/**
 * Server Component: Fetches security stats 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 SecurityDashboard() {
  // Server-side: Validate staff session and fetch security stats
  const session = await getStaffSession();

  let initialStats: SecurityStats | null = null;

  // Only fetch stats if user is ADMIN or SUPER_ADMIN
  if (session && (session.role === "ADMIN" || session.role === "SUPER_ADMIN")) {
    try {
      const stats = await getSecurityStats();

      // Convert Date objects to strings for serialization
      initialStats = {
        totalLogins24h: stats.totalLogins24h,
        failedLogins24h: stats.failedLogins24h,
        uniqueUsers24h: stats.uniqueUsers24h,
        uniqueCountries24h: stats.uniqueCountries24h,
        suspiciousActivities: stats.suspiciousActivities.map((activity) => ({
          type: activity.type,
          userId: activity.userId,
          userEmail: activity.userEmail,
          userName: activity.userName,
          details: activity.details,
          count: activity.count,
          lastOccurrence: activity.lastOccurrence.toISOString(),
        })),
      };
    } catch (error) {
      console.error("Failed to fetch security stats:", error);
      // Fallback to null - client will show empty state
    }
  }

  return <SecurityDashboardClient initialStats={initialStats} />;
}
