import { AxiosResponse } from 'axios';

import { queryClient } from 'src/config/react-query';
import { CategoryTask, OnboardingStatus } from 'src/types/onboarding';

export const onBoardingKeys = {
  all: () => ['onboarding'],
  categories: () => [...onBoardingKeys.all(), 'categories'],
  tasks: {
    list: (id: number | string) => [
      ...onBoardingKeys.categories(),
      Number(id),
      'tasks',
    ],
    detail: (taskId: number | string, categoryId: number | string) => [
      ...onBoardingKeys.tasks.list(categoryId),
      Number(taskId),
    ],
  },
  quiz: {
    all: () => [...onBoardingKeys.all(), 'quizes'],
    allDetail: () => [...onBoardingKeys.quiz.all(), 'detail'],
    detail: (categoryId: number | string, taskId: number | string) => [
      ...onBoardingKeys.quiz.allDetail(),
      Number(categoryId),
      Number(taskId),
    ],
    completed: {
      all: () => [...onBoardingKeys.quiz.all(), 'completed'],
      allDetail: () => [...onBoardingKeys.quiz.completed.all(), 'detail'],
      detail: (userId: number | string, quizId: number | string) => [
        ...onBoardingKeys.quiz.completed.allDetail(),
        Number(userId),
        Number(quizId),
      ],
    },
  },
  notifications: {
    all: () => [...onBoardingKeys.all(), 'notifications'],
    module: () => [...onBoardingKeys.notifications.all(), 'module'],
  },
};

export const isCategoryListInCache = (categoryId: number | string): boolean => {
  const categoryListData: AxiosResponse<CategoryTask[]> =
    queryClient.getQueryData(onBoardingKeys.tasks.list(categoryId));

  if (!categoryListData?.data.length) return false;

  return true;
};

export const getTasksOfCategory = (
  categoryId: number | string,
): CategoryTask[] => {
  const categoryListData: AxiosResponse<CategoryTask[]> =
    queryClient.getQueryData(onBoardingKeys.tasks.list(categoryId));

  if (!categoryListData?.data.length) return [];

  return categoryListData?.data;
};

export const updateTaksOfCategory = (categoryId: string, taskId: string) => {
  queryClient.setQueryData(
    onBoardingKeys.tasks.list(categoryId),
    (oldData: AxiosResponse<CategoryTask[]>) => {
      if (!oldData) return oldData;

      const task = oldData.data.find(item => item.task.id === Number(taskId));
      task.status = OnboardingStatus.DONE;

      return oldData;
    },
  );
};

// Notifications

export const invalidateOnboardingNotifications = () =>
  queryClient.invalidateQueries(onBoardingKeys.notifications.module());

export const addOnboarding = () => {
  invalidateOnboardingNotifications();
  queryClient.invalidateQueries(onBoardingKeys.categories());
};

export const deleteOnboarding = () => {
  invalidateOnboardingNotifications();
  queryClient.invalidateQueries(onBoardingKeys.categories());
};
