import qs from 'qs';

import api from 'src/config/api';

import {
  type ContentModule,
  type SearchFilter,
  type SearchResult,
} from './types';

const FILTER_MODULE: Record<
  SearchFilter,
  ContentModule[] | ContentModule | undefined
> = {
  all: undefined,
  person: 'USERS',
  post: ['FEED', 'GROUP_POSTS', 'ARTICLES'],
  group: 'GROUPS',
};

export type SearchResponse = {
  results: SearchResult[];
  nextCursor: string | null;
};

export const searchGlobal = async (
  q: string,
  filter: SearchFilter,
  options?: {
    limit?: number;
    cursor?: string;
  },
) => {
  const { limit, cursor } = options ?? {};
  let modules = FILTER_MODULE[filter];

  if (!modules) {
    const queryLength = q.length;

    if (queryLength === 1) {
      modules = 'USERS';
    }

    if (queryLength === 2) {
      modules = ['GROUPS', 'USERS'];
    }
  }

  const res = await api.get<SearchResponse>('heimdall/search', {
    params: {
      q,
      ...(modules && { modules }),
      ...(cursor && { cursor }),
      ...(limit && { limit }),
    },
    paramsSerializer: params => qs.stringify(params, { arrayFormat: 'comma' }),
  });

  return res.data;
};
