import api from 'src/config/api';
import { queryClient } from 'src/config/react-query';
import { onBoardingKeys } from 'src/pages/dashboard/onboarding/queries';
import { createForm, getForm } from 'src/services/forms';
import {
  QuizAnswer,
  OnboardingsNotificationsResponse,
} from 'src/types/onboarding';

export const getOnboardings = userId => api.get(`/users/${userId}/onboardings`);

export const getOnboardingTasks = ({ userId, categoryId }) =>
  api.get(`/users/${userId}/onboardings/categories/${categoryId}/tasks`);

export const getOnboardingTasksDetail = async (userId, categoryId, tasksId) => {
  const data = await queryClient.fetchQuery(
    onBoardingKeys.tasks.list(categoryId),
    () => getOnboardingTasks({ userId, categoryId }),
  );
  const tasks = data?.data;
  return tasks?.find(item => item.task.id === Number(tasksId));
};

export const finalizeOnboardingTask = ({ userId, taskId }) =>
  api.patch(`/users/${userId}/onboardings/tasks/${taskId}`, { status: 'DONE' });

export const getOnboardingQuiz = taskId =>
  api.get(`/onboardings/tasks/${taskId}/quiz`);

export const completeOnboardingTask = async ({
  userId,
  taskId,
  quizId,
  body,
}) => {
  const { data: form } = await getForm(quizId);
  await createForm(form.id, body);
  return finalizeOnboardingTask({ userId, taskId });
};

export const getQuizAnswer = (userId, taskId) =>
  api.get<QuizAnswer>(
    `/users/${userId}/onboardings/tasks/${taskId}/quiz-answer`,
  );

// Notifications
export const getOnboardingsNotifications = () =>
  api.get<OnboardingsNotificationsResponse>('red-bubbles/onboardings');
