import api from 'src/config/api';

import { DynamicForm, DynamicFormBody, DynamicFormResponse } from './types';

const initDynamicForm = async ({
  progressionToken,
  tag,
}: InitDynamicFormParams) => {
  const response = await api.post<DynamicFormResponse>(
    `/dynamic-forms/${encodeURIComponent(tag)}/progressions`,
    null,
    { params: { token: progressionToken } },
  );
  return response.data;
};

const updateDynamicFormProgression = async ({
  body,
  progressionId,
  tag,
}: UpdateDynamicFormProgressionParams) => {
  const response = await api.patch<DynamicFormResponse>(
    `/dynamic-forms/${tag}/progressions/${progressionId}`,
    body,
  );
  return response.data;
};

const getDynamicFormAnswer = async ({
  tag,
  answerId,
  answerToken,
}: GetDynamicFormAnswerParams) => {
  const response = await api.get<DynamicForm>(
    `/dynamic-forms/${tag}/answers/${answerId}`,
    { params: { token: answerToken, withDetails: true } },
  );
  return response.data;
};

const getDynamicFormProgress = async ({
  tag,
  progressionId,
}: GetDynamicFormProgressParams) => {
  const response = await api.get<DynamicFormResponse>(
    `/dynamic-forms/${tag}/progressions/${progressionId}`,
  );
  return response.data;
};

export {
  initDynamicForm,
  updateDynamicFormProgression,
  getDynamicFormAnswer,
  getDynamicFormProgress,
};

type InitDynamicFormParams = {
  progressionToken: string;
  tag: string;
};
type UpdateDynamicFormProgressionParams = {
  tag: string;
  progressionId: string;
  body: DynamicFormBody;
};
type GetDynamicFormAnswerParams = {
  tag: string;
  answerId: number;
  answerToken: string;
};
type GetDynamicFormProgressParams = {
  tag: string;
  progressionId: string;
};
