import {
  loadDashboardRuntime,
  type DashboardRuntimeOptions,
  type DashboardRuntimeState,
} from "$lib/server/dashboard";
import { resolveDashboardDatasources } from "$lib/server/datasources";

export interface LoadDashboardResponseOptions
  extends Pick<
    DashboardRuntimeOptions,
    "refreshSeedDocument" | "seedIfEmpty" | "seedDocument"
  > {
  disableLiveDatasources?: boolean;
}

export async function loadDashboardResponse(
  options: LoadDashboardResponseOptions = {},
): Promise<DashboardRuntimeState> {
  const dashboard = loadDashboardRuntime(undefined, {
    refreshSeedDocument: options.refreshSeedDocument ?? true,
    seedIfEmpty: options.seedIfEmpty ?? true,
    seedDocument: options.seedDocument,
  });

  if (dashboard.state !== "ready") {
    return dashboard;
  }

  if (options.disableLiveDatasources || process.env.DISABLE_LIVE_DATASOURCES === "1") {
    return dashboard;
  }

  return {
    ...dashboard,
    document: await resolveDashboardDatasources(dashboard.document),
  };
}

export async function handleDashboardRoute(): Promise<Response> {
  return Response.json(await loadDashboardResponse());
}
