import { getActiveClient } from '~/client/api';

import { toPage, toToken } from '~/core/query';
import { ingestInCache } from '~/cache/api/ingestInCache';

/* begin_public_function
  id: stream.query
*/
/**
 * ```js
 * import { getStreams } from '@amityco/ts-sdk-react-native'
 * const streams = await getStreams()
 * ```
 *
 * Queries a paginable list of {@link Amity.Stream} objects
 *
 * @param query The query parameters
 * @returns A page of {@link Amity.Stream} objects
 *
 * @category Stream API
 * @async
 */
export const getStreams = async (query?: {
  isLive?: boolean;
  statuses?: Amity.StreamStatus[];
  userPublicIds?: Amity.InternalUser['userId'][];
  sortBy?: 'lastCreated' | 'firstCreated';
  isDeleted?: Amity.Stream['isDeleted'];
  page?: Amity.Page;
}): Promise<Amity.Cached<Amity.Paged<Amity.Stream>>> => {
  const client = getActiveClient();
  client.log('stream/getStreams', query);

  const { page, ...params } = query ?? {};

  const { data } = await client.http.get<{ results: Amity.StreamPayload } & Amity.Pagination>(
    `/api/v3/video-streaming`,
    {
      params: {
        ...params,
        options: {
          token: toToken(page, 'skiplimit'),
        },
      },
    },
  );

  // API-FIX: backend to response Amity.Response: const { paging, videoStreamings } = unwrapPayload(data)
  // API-FIX: seems returned data has a results identifier on top of data, like no other apis, and this is beautiful
  const { paging, results: payload } = data;
  const { videoStreamings } = payload;

  const cachedAt = client.cache && Date.now();
  if (client.cache) ingestInCache(payload as Amity.StreamPayload, { cachedAt });

  const nextPage = toPage(paging.next);
  const prevPage = toPage(paging.previous);

  return { data: videoStreamings, cachedAt, prevPage, nextPage };
};
/* end_public_function */

/**
 * ```js
 * import { getStreams } from '@amityco/ts-sdk-react-native'
 * const streams = getStreams.locally()
 * ```
 *
 * Queries a paginable list of {@link Amity.Stream} objects from cache
 *
 * @param query The query parameters
 * @returns streams
 *
 * @category Stream API
 */
getStreams.locally = (query: Parameters<typeof getStreams>[0]) => {
  const client = getActiveClient();
  client.log('stream/getStreams.locally', query);

  // TODO
};
