import { DashboardHomePage } from "../features/Pages/DashboardHomePage/DashboardHomePage";
import { transformHealthDataToStats } from "../features/GeneralHealthCard/utils";
import { fetchDashboardDataService } from "../services/health";
import { getDefaultDateRange } from "../utils/formatDate";

export default async function DashboardPage() {
  // Fetch all dashboard data (health, overview, and review transactions) concurrently with default 24h range
  const defaultDates = getDefaultDateRange();
  let initialHealthData = null;
  let initialStats = null;
  let initialOverviewData = null;
  let initialReviewTransactions = null;

  try {
    const dashboardData = await fetchDashboardDataService({
      dateStart: defaultDates.dateStart,
      dateEnd: defaultDates.dateEnd,
    });

    const { healthData, overviewData, reviewTransactions } = dashboardData;
    initialHealthData = healthData;
    initialStats = healthData.stats ?? transformHealthDataToStats(healthData);
    initialOverviewData = overviewData;
    initialReviewTransactions = reviewTransactions;
  } catch (_error: unknown) {
    // If fetch fails, component will handle it client-side
    const error = _error as Error;
    console.error("Failed to fetch dashboard data:", error.cause);
  }

  return (
    <DashboardHomePage
      initialHealthData={initialHealthData}
      initialStats={initialStats}
      initialDateRange={[
        {
          startDate: new Date(defaultDates.dateStart),
          endDate: new Date(defaultDates.dateEnd),
          key: "selection",
        },
      ]}
      initialOverviewData={initialOverviewData}
      initialReviewTransactions={initialReviewTransactions}
    />
  );
}
