import { AnalyticsControllerGetAnalyticsForEnvDateSelectionEnum } from "@montelo/browser-client";
import { defer } from "@remix-run/node";
import { useLoaderData } from "@remix-run/react";
import { withAuth } from "~/auth/withAuth";
import { DashboardPage } from "~/pages/dashboard/DashboardPage";
import { formatLogDates } from "~/pages/dashboard/utils";
import { getTimezone } from "~/services/timezone.server";
import { DashboardLoader, DeferredDashboardLoader } from "~/types/DashboardLoader.types";

export const loader = withAuth(async ({ request, api, params }) => {
  const envId = params.envId!;
  const { searchParams } = new URL(request.url);
  const dateSelectionQuery = (searchParams.get("dateSelection") ||
    AnalyticsControllerGetAnalyticsForEnvDateSelectionEnum._30Mins) as AnalyticsControllerGetAnalyticsForEnvDateSelectionEnum;
  const analyticsPromise = api.analytics.analyticsControllerGetAnalyticsForEnv({
    envId,
    dateSelection: dateSelectionQuery,
  });
  const costHistoryPromise = api.analytics.analyticsControllerGetCostHistoryForEnv({
    envId,
    dateSelection: dateSelectionQuery,
  });
  const { logs } = await api.log.logControllerGetLogsForEnvironment({
    envId,
    take: "25",
  });

  // formatting
  const timezone = await getTimezone(request);
  const formattedLogs = formatLogDates(logs, timezone);

  return defer<DeferredDashboardLoader>({
    analytics: analyticsPromise,
    logs: formattedLogs,
    costHistory: costHistoryPromise,
    timezone,
  });
});

export default function DashboardRoute() {
  const { analytics, logs, costHistory, timezone } = useLoaderData<DashboardLoader>();

  const formattedLogs = timezone ? logs : formatLogDates(logs, timezone);

  return <DashboardPage analytics={analytics} logs={formattedLogs} costHistory={costHistory} />;
}
