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

/* ---------- params accepted by this helper --------------------- */
interface FetchBoardsParams {
  sortOrder?: 'asc' | 'desc';
  pageNumber?: number;
  itemsPerPage?: number;
  access?: BoardAccessMode;
  pageToken?: string;
}

const FUNCTION_BASE = 'https://fetchboards-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 ? 'fetchBoardsCursor' : 'fetchBoards';

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

  return await $fetch<CursorResponse<T>>(`${FUNCTION_BASE}/${endpoint}`, {
    method: 'GET',
    params,
    credentials: access !== 'public' ? 'include' : undefined,
  });
}
