import type {
  MyPaperListItem,
  MyPaperPageQuery,
  OnlineExamDetail,
  OnlineExamPaper,
  OnlineExamSubmitResult,
} from '#/views/x/tms/onlineExam/types';

import { defHttp } from '#/api/request';

const prefix = '/api/tms/online-exam';

async function unwrapData<T>(promise: Promise<any>): Promise<T> {
  const res = await promise;
  if (res && typeof res === 'object' && 'data' in res && ('code' in res || 'msg' in res)) {
    return res.data as T;
  }
  return res as T;
}

export function getMyPaperList(params: MyPaperPageQuery) {
  return unwrapData<{ list: MyPaperListItem[]; pagination: Record<string, any> }>(
    defHttp.get({ url: `${prefix}/my-papers`, params }),
  );
}

export function getMyPaperDetail(id: string) {
  return unwrapData<OnlineExamDetail>(defHttp.get({ url: `${prefix}/my-papers/${id}` }));
}

export function getExamReview(examId: string) {
  return unwrapData<OnlineExamDetail>(defHttp.get({ url: `${prefix}/exams/${examId}` }));
}

export function startOnlineExam(myPaperId: string) {
  return unwrapData<OnlineExamPaper>(
    defHttp.post({ url: `${prefix}/start`, data: { myPaperId } }, { errorMessageMode: 'none' }),
  );
}

export function saveOnlineExam(examId: string, answers: Record<string, string | string[]>) {
  return unwrapData(
    defHttp.post({ url: `${prefix}/${examId}/save`, data: { answers } }, { errorMessageMode: 'none' }),
  );
}

export function submitOnlineExam(examId: string, answers: Record<string, string | string[]>) {
  return unwrapData<OnlineExamSubmitResult>(
    defHttp.post({ url: `${prefix}/${examId}/submit`, data: { answers } }, { errorMessageMode: 'none' }),
  );
}
