import { makeRequest } from "@frontend/kitui";

import { parseAxiosError } from "@utils/parse-error";

import type { RawResult } from "@model/result/result";

interface IResultListBody {
  to: number;
  from: string;
  new: boolean;
  page: number;
  limit: number;
}

export interface IAnswerResult {
  Browser: string;
  CreatedAt: string;
  Deleted: boolean;
  Device: string;
  DeviceType: string;
  Email: string;
  Fingerprint: string;
  IP: string;
  Id: number;
  OS: string;
  QuizId: number;
  Result: boolean;
  Session: string;
  Start: boolean;
  content: string;
  new: boolean;
  question_id: number;
}

type ResultFilter = {
  from?: string;
  new?: boolean;
  to?: string;
};

type ObsolescenceRequest = {
  answers: number[];
};

const API_URL = `${process.env.REACT_APP_DOMAIN}/squiz`;

const getResultList = async (
  quizId: number,
  page: number,
  body: ResultFilter,
): Promise<[RawResult | null, string?]> => {
  try {
    const resultList = await makeRequest<IResultListBody, RawResult>({
      method: "POST",
      url: `${API_URL}/results/getResults/${quizId}`,
      body: { page: page, limit: 10, ...body },
    });

    return [resultList];
  } catch (nativeError) {
    const [error] = parseAxiosError(nativeError);

    return [null, `Не удалось получить результат. ${error}`];
  }
};

const deleteResult = async (
  resultId: number,
): Promise<[string | null, string?]> => {
  try {
    const deletedResult = await makeRequest<void, string>({
      method: "DELETE",
      url: `${API_URL}/results/delete/${resultId}`,
      body: {},
    });

    return [deletedResult];
  } catch (nativeError) {
    const [error] = parseAxiosError(nativeError);

    return [null, `Не удалось удалить результат. ${error}`];
  }
};

const obsolescenceResult = async (
  idResultArray: number[],
): Promise<[null, string?]> => {
  try {
    const obsolescencedResult = await makeRequest<ObsolescenceRequest, null>({
      method: "PATCH",
      url: `${API_URL}/result/seen`,
      body: { answers: idResultArray },
    });

    return [obsolescencedResult];
  } catch (nativeError) {
    const [error] = parseAxiosError(nativeError);

    return [null, `Не удалось изменить результат. ${error}`];
  }
};

const getAnswerResultList = async (
  resultId: number,
): Promise<[IAnswerResult[] | null, string?]> => {
  try {
    const answerResultList = await makeRequest<never, IAnswerResult[]>({
      method: "GET",
      url: `${API_URL}/result/${resultId}`,
    });

    return [answerResultList];
  } catch (nativeError) {
    const [error] = parseAxiosError(nativeError);

    return [null, `Не удалось получить список результатов. ${error}`];
  }
};

const AnswerResultListEx = async (
  quizId: number,
  body: ResultFilter,
): Promise<[Blob | null, string?]> => {
  try {
    const answerResultListEx = await makeRequest<ResultFilter, Blob>({
      method: "POST",
      url: `${API_URL}/results/${quizId}/export`,
      body,
      responseType: "blob",
    });

    return [answerResultListEx];
  } catch (nativeError) {
    const [error] = parseAxiosError(nativeError);

    return [
      null,
      `Не удалось получить список устаревших результатов. ${error}`,
    ];
  }
};

export const resultApi = {
  getList: getResultList,
  delete: deleteResult,
  getAnswerList: getAnswerResultList,
  export: AnswerResultListEx,
  obsolescence: obsolescenceResult,
};
