import api, {HEADERS} from '@config/api';

import {
  GetReactionsResponse,
  GetReactionsParams,
  ToggleReactionParams,
  ToggleReactionResponse,
} from './interfaces';
import {CHATS_BASE_URL} from './constants';
import {getUsersInfo} from './usersServices';
import {mapReactionWithUserInfo} from '../utils/mappers/reactionMapper';

export const toggleReaction = async (params: ToggleReactionParams) => {
  const response = await api.post<ToggleReactionResponse>(
    `${CHATS_BASE_URL}/reactions.${params.type}`,
    {
      channel: params.channel,
      ts: params.ts,
      name: params.name,
    },
    {headers: {[HEADERS.IDEMPOTENCY_KEY]: params.idempotencyKey}},
  );

  if (!response.ok || !response.data?.ok) {
    throw new Error(response.problem || 'Failed to toggle reaction');
  }

  return response.data;
};

export const getReactions = async (params: GetReactionsParams) => {
  const response = await api.get<GetReactionsResponse>(
    `${CHATS_BASE_URL}/reactions.get`,
    params,
  );

  if (!response.ok || !response.data?.ok) {
    throw new Error(response.problem || 'Failed to get reactions');
  }

  if (!response.data.message.reactions?.length) {
    return [];
  }

  const users = await getUsersInfo(
    response.data.message.reactions
      ?.flatMap(reaction => reaction.users)
      .map(Number)
      .filter(userId => !isNaN(userId)) || [],
  );

  return mapReactionWithUserInfo({
    serviceData: response.data.message.reactions,
    users,
  });
};
