/**
 * System Messages Manager Server Component
 *
 * Server-side wrapper that pre-fetches system messages 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 { getStaffSession } from "@/lib/staff-session";
import SystemMessagesManagerClient from "./SystemMessagesManagerClient";
import type { SystemMessage } from "./SystemMessagesManagerClient";

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

  let initialMessages: SystemMessage[] = [];

  // Only fetch messages if user is ADMIN or SUPER_ADMIN
  if (user && (user.role === "ADMIN" || user.role === "SUPER_ADMIN")) {
    try {
      const messages = await prisma.system_messages.findMany({
        orderBy: { createdAt: "desc" },
        include: {
          _count: {
            select: { system_message_views: true },
          },
        },
      });

      // Convert to client-friendly format with string dates
      initialMessages = messages.map((msg) => ({
        id: msg.id,
        type: msg.type as "info" | "warning" | "error" | "maintenance",
        title: msg.title,
        message: msg.message,
        isActive: msg.isActive,
        createdAt: msg.createdAt.toISOString(),
        expiresAt: msg.expiresAt?.toISOString() || null,
        _count: {
          views: msg._count.system_message_views,
        },
      }));
    } catch (error) {
      console.error("Failed to fetch system messages:", error);
      // Fallback to empty array - client can refetch
    }
  }

  // If user is not valid, return empty state (will show login prompt or error)
  if (!user) {
    return (
      <SystemMessagesManagerClient
        initialMessages={[]}
        user={{ id: "", role: "" }}
      />
    );
  }

  return (
    <SystemMessagesManagerClient
      initialMessages={initialMessages}
      user={{ id: user.id, role: user.role }}
    />
  );
}
