
import { HomePageClient } from "@/components/home-page-client";
import { db } from "@/lib/firebase";
import { ref, get, query, orderByChild, equalTo } from "firebase/database";
import type { Stream, User, UploadedVideo, ViewLog } from "@/types";

async function getStreams(): Promise<Stream[]> {
  try {
    const streamsRef = ref(db, 'streams');
    const snapshot = await get(streamsRef);
    if (snapshot.exists()) {
      const streamsData = snapshot.val();
      return Object.keys(streamsData)
        .map(key => ({ id: key, ...streamsData[key] }))
        .filter(stream => stream.status === 'approved');
        // Sorting is now handled in HomePageClient to ensure it's always up-to-date
    }
    return [];
  } catch (error) {
    console.error("Error fetching streams server-side:", error);
    return [];
  }
}

async function getUsers(): Promise<User[]> {
  try {
    const usersRef = ref(db, 'users');
    const snapshot = await get(usersRef);
    if (snapshot.exists()) {
      const usersData = snapshot.val();
      return Object.keys(usersData).map(key => ({ id: key, ...usersData[key] }));
    }
    return [];
  } catch (error) {
    console.error("Error fetching users server-side:", error);
    return [];
  }
}

async function getApprovedVideos(): Promise<UploadedVideo[]> {
    try {
        const videosQuery = query(ref(db, 'videos'), orderByChild('status'), equalTo('approved'));
        const snapshot = await get(videosQuery);
        if (snapshot.exists()) {
            const videosData = snapshot.val();
            return Object.keys(videosData)
                .map(key => ({ id: key, ...videosData[key] }))
                .sort((a, b) => (b.actionedAt || 0) - (a.actionedAt || 0));
        }
        return [];
    } catch (error) {
        console.error("Error fetching approved videos server-side:", error);
        return [];
    }
}

async function getViewLogs(): Promise<ViewLog[]> {
  try {
    const viewLogsRef = ref(db, 'view_logs');
    const snapshot = await get(viewLogsRef);
    if (snapshot.exists()) {
      const logsData = snapshot.val();
      return Object.keys(logsData).map(key => ({ id: key, ...logsData[key] }));
    }
    return [];
  } catch (error) {
    console.error("Error fetching view logs server-side:", error);
    return [];
  }
}

export default async function Home({
  searchParams: searchParamsPromise,
}: {
  searchParams: Promise<{ [key: string]: string | string[] | undefined }>;
}) {
  const searchParams = await searchParamsPromise;
  const streamId = typeof searchParams?.stream === 'string' ? searchParams.stream : null;
  
  // Fetch all data server-side
  const streams = await getStreams();
  const users = await getUsers();
  const approvedVideos = await getApprovedVideos();
  const viewLogs = await getViewLogs();

  // Find the initial stream to show, if any. This is safe to do server-side.
  const initialSelectedStream = streamId
    ? streams.find((s) => s.id === streamId) || null
    : null;

  return (
    <HomePageClient
      initialStreams={streams}
      initialUsers={users}
      initialApprovedVideos={approvedVideos}
      initialSelectedStream={initialSelectedStream}
      initialViewLogs={viewLogs}
    />
  );
}
