import type { SelfTestPaper, SelfTestQuestionItem, SelfTestStartPayload } from './types';

import { mockGetQuestion, mockQueryQuestions } from '#/views/x/tms/question/mock';

import { SELF_TEST_DIFFICULTY_TO_QUESTION, type SelfTestDifficulty } from './constants';

function delay<T>(data: T, ms = 250): Promise<T> {
  return new Promise((resolve) => setTimeout(() => resolve(data), ms));
}

/** 按条件从 mock 题库抽题（不够则放宽难度） */
export async function mockStartSelfTest(payload: SelfTestStartPayload): Promise<SelfTestPaper> {
  const all = await mockQueryQuestions({ bankId: payload.bankId, pageSize: 500, currentPage: 1 });
  const list = all.list || [];

  const pick = async (type: 'single' | 'multi' | 'judge', count: number, difficulty: SelfTestDifficulty) => {
    if (count <= 0) return [];
    const mapped = SELF_TEST_DIFFICULTY_TO_QUESTION[difficulty] || [difficulty];
    let pool = list.filter((q) => q.questionType === type);
    if (difficulty) {
      pool = pool.filter((q) => !q.difficulty || mapped.includes(q.difficulty));
    }
    // 不够则放宽难度
    if (pool.length < count) {
      pool = list.filter((q) => q.questionType === type);
    }
    const sliced = pool.slice(0, count);
    const detailed: SelfTestQuestionItem[] = [];
    for (const q of sliced) {
      const full = await mockGetQuestion(q.id!);
      detailed.push({
        id: full.id!,
        questionNo: full.questionNo,
        questionType: full.questionType as 'single' | 'multi' | 'judge',
        difficulty: full.difficulty,
        stem: full.stem,
        options: (full.options || []).map((o) => ({
          optionLabel: o.optionLabel,
          optionContent: o.optionContent,
          isCorrect: o.isCorrect,
        })),
      });
    }
    return detailed;
  };

  const questions = [
    ...(await pick('single', payload.single.count, payload.single.difficulty)),
    ...(await pick('multi', payload.multi.count, payload.multi.difficulty)),
    ...(await pick('judge', payload.judge.count, payload.judge.difficulty)),
  ];

  return delay({
    paperId: `self_${Date.now()}`,
    bankId: payload.bankId,
    bankName: payload.bankName || '',
    questions,
  });
}
