import { AnyTypedQuizQuestion } from "@model/questionTypes/shared";
import { QuizSettings } from "@model/settingsData";

export interface GetQuizDataResponse {
  cnt: number;
  settings?: {
    fp: boolean;
    rep: boolean;
    name: string;
    cfg: string;
    lim: number;
    due: number;
    delay: number;
    pausable: boolean;
    status: "start" | "stop" | "ai";
  };
  items: {
    id: number;
    title: string;
    desc: string;
    typ: string;
    req: boolean;
    p: number;
    c: string;
  }[];
  show_badge: boolean;
}

export function parseQuizData(quizDataResponse: GetQuizDataResponse): Omit<QuizSettings, "recentlyCompleted"> {
  const readyData = {
    cnt: quizDataResponse.cnt,
    show_badge: quizDataResponse.show_badge,
    settings: {} as QuizSettings["settings"],
    questions: [] as QuizSettings["questions"],
  } as QuizSettings;

  const items: QuizSettings["questions"] = quizDataResponse.items.map((item) => {
    const content = item.c
      ? JSON.parse(item.c)
      : {
          hint: { text: "", video: "" },
          rule: { children: [], main: [], parentId: "", default: "" },
          back: "",
          originalBack: "",
          autofill: false,
          placeholder: "",
          innerNameCheck: false,
          innerName: "",
          required: false,
          answerType: "single",
          onlyNumbers: false,
        };
    // Убираю замену ID - оставляю оригинальный с бэкенда
    // if (item.c) content.id = Math.floor(Math.random() * 9999999999) + 1;
    return {
      description: item.desc,
      id: item.id,
      page: item.p,
      required: item.req,
      title: item.title,
      type: item.typ,
      content,
    } as unknown as AnyTypedQuizQuestion;
  });

  readyData.questions = items;

  if (quizDataResponse?.settings !== undefined) {
    const parsedCfg = JSON.parse(quizDataResponse?.settings.cfg);

    readyData.settings = {
      fp: quizDataResponse.settings.fp,
      rep: quizDataResponse.settings.rep,
      name: quizDataResponse.settings.name,
      cfg: parsedCfg,
      lim: quizDataResponse.settings.lim,
      due: quizDataResponse.settings.due,
      delay: quizDataResponse.settings.delay,
      pausable: quizDataResponse.settings.pausable,
      status: quizDataResponse.settings.status,
      // Автоматически включаем таймер, если time_of_passing > 0
      questionTimerEnabled: parsedCfg.time_of_passing > 0,
    };
  }

  return readyData;
}
