import { useRuntimeConfig } from '#imports';
import type { BoardItem, BoardAccessMode, CursorResponse } from '~/types';

interface FetchBoardsParams {
  sortOrder?: 'asc' | 'desc';
  pageNumber?: number;
  itemsPerPage?: number;
  access?: BoardAccessMode;
  pageToken?: string;
}

// ⛳️ Split base URLs per function (if deployed separately)
const BASE_FETCH_BOARDS = 'https://fetchboards-edvvp3hbnq-du.a.run.app';
const BASE_FETCH_BOARDS_CURSOR =
  'https://fetchboardscursor-edvvp3hbnq-du.a.run.app';

export async function fetchBoardsFromFunction<T extends BoardItem>(
  collection: string,
  {
    sortOrder = 'desc',
    pageNumber = 1,
    itemsPerPage = 10,
    access = 'public',
    pageToken,
  }: FetchBoardsParams = {}
): Promise<CursorResponse<T>> {
  const isCursorMode = !!pageToken || pageNumber === undefined;
  const endpoint = isCursorMode ? BASE_FETCH_BOARDS_CURSOR : BASE_FETCH_BOARDS;

  const params: Record<string, any> = {
    collection,
    sortOrder,
    itemsPerPage,
    access,
    ...(isCursorMode ? { pageToken } : { pageNumber }),
  };

  const result = await $fetch(endpoint, {
    method: 'GET',
    params,
    credentials: access !== 'public' ? 'include' : undefined,
  });

  return result as CursorResponse<T>;
}
