import { useVisitor }                                 from '@/stores';
import HTTP                                           from '../alova';
import type { QuestionnaireStorage }                  from '../model';
import { fromQuestionnaireData, toQuestionnaireData } from '../model';


const visitor = useVisitor();
let storage: Pick<QuestionnaireStorage, 'dialogId'> & { questions: QuestionnaireStorage['questions'][] } = { questions: [] };

export function questionnaireMethod(data = []) {
  if ( !data?.length ) { storage = { questions: [] }; }
  const step = storage.questions.length;
  return HTTP.Post(
    `/fdhb-tablet/dialogueManage/dialog/${ visitor.patientId }/${ visitor.resultId }`,
    { step, ...toQuestionnaireData(data, { dialogId: storage.dialogId, questions: storage.questions[ step - 1 ] }) },
    {
      transform(data: Record<string, any>, headers) {
        const { storage: { dialogId, questions }, model } = fromQuestionnaireData(data);
        storage = { dialogId, questions: questions.length ? [ ...storage.questions, questions ] : [] };
        return model;
      },
    },
  );
}
