import api from 'src/config/api';
import { Comment, PostCommentPayload } from 'src/types/comments';
import {
  Article,
  ArticleTopics,
  NewsNotificationsResponse,
} from 'src/types/news';
import { ReactionUsersResponse } from 'src/types/reaction';
import { TaggedUser } from 'src/types/user';

export const getArticleList = (
  timestamp: string | undefined,
  topicId: number | null,
  q?: string,
) =>
  api.get<Article[]>('articles', {
    params: {
      timestamp: timestamp ? new Date(timestamp).toISOString() : undefined,
      topicIds: topicId ?? undefined,
      q: q || undefined,
    },
  });

export const getArticleById = (id: string) =>
  api.get<Article>(`articles/${id}`);

export const getArticlesTopics = () =>
  api.get<ArticleTopics[]>('articles/topics');

export const addArticleReaction = (
  id: number,
  emoji: string,
  unified: string,
) => api.post(`articles/${id}/reactions/add`, { emoji, unified });

export const removeArticleReaction = (id: number, emoji: string) =>
  api.post(`articles/${id}/reactions/remove`, { emoji });

export const getArticleReactionUsers = (
  articleId: number,
  emoji: string,
  timestamp?: string,
) =>
  api.get<ReactionUsersResponse>(`articles/${articleId}/reactions/users`, {
    params: { emoji, timestamp },
  });

export const getArticleComments = (id: number, limit: number, page?: number) =>
  api.get<Comment[]>(`articles/${id}/comments`, {
    params: {
      orderBy: 'CREATED_AT',
      order: 'DESC',
      limit,
      page,
    },
  });

export const getChildCommentsPaginated = (
  id: number,
  parentId: number,
  page: number,
  limit: number,
) =>
  api.get<Comment[]>(`articles/${id}/comments`, {
    params: {
      page,
      limit,
      parentId,
      orderBy: 'CREATED_AT',
      order: 'DESC',
    },
  });

export const postComment = (id: number, data: PostCommentPayload) =>
  api.post<Comment>(`articles/${id}/comments`, data);

// Notifications
export const getNewsNotifications = () =>
  api.get<NewsNotificationsResponse>('red-bubbles/articles');

export const clearNewsNotifications = () =>
  api.post('red-bubbles/articles/clear');

export const notifyArticleCommentUsers = (
  articleId: number,
  bodyAttributes: TaggedUser[],
) => {
  const mentionedUserIds = bodyAttributes.map(
    attribute => attribute.type.user.id,
  );
  return api.post(`/articles/${articleId}/comments/mentions`, {
    userIds: mentionedUserIds,
  });
};
