/**
 * Staff Management Server Component
 *
 * Server-side wrapper that pre-fetches staff list 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 { requireSuperAdminAuth } from "@/lib/staff-auth";
import StaffManagementClient from "./StaffManagementClient";
import type { StaffMember } from "./StaffManagementClient";

/**
 * Server Component: Fetches staff list 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 StaffManagement() {
  // Server-side: Validate super admin auth and fetch staff
  const user = await requireSuperAdminAuth();

  let initialStaff: StaffMember[] = [];

  try {
    const staff = await prisma.users.findMany({
      where: {
        role: { in: ["STAFF", "ADMIN", "SUPER_ADMIN"] },
      },
      orderBy: { createdAt: "desc" },
      select: {
        id: true,
        name: true,
        email: true,
        username: true,
        role: true,
        isActive: true,
        lastLoginAt: true,
        createdAt: true,
      },
    });

    // Convert Date objects to strings for serialization
    initialStaff = staff.map((member) => ({
      id: member.id,
      name: member.name || "",
      email: member.email,
      username: member.username || "",
      role: member.role,
      isActive: member.isActive,
      lastLoginAt: member.lastLoginAt?.toISOString() || null,
      createdAt: member.createdAt.toISOString(),
    }));
  } catch (error) {
    console.error("Failed to fetch staff:", error);
    // Fallback to empty array - client can refetch
  }

  return (
    <StaffManagementClient
      initialStaff={initialStaff}
      currentUser={{ id: user.id, role: user.role }}
    />
  );
}
