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

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

export type DevicesResponse = {
  Device: Record<string, number>;
  OS: Record<string, number>;
  Browser: Record<string, number>;
};

export type GeneralResponse = {
  Open: Record<string, number>;
  Result: Record<string, number>;
  AvTime: Record<string, number>;
  Conversion: Record<string, number>;
};

export type QuestionsResponse = {
  Funnel: number[];
  FunnelData: number[];
  Results: Record<string, number>;
  Questions: Record<string, Record<string, number>>;
};
export type GraphicsResponse = unknown;

type TRequest = {
  to: number;
  from: number;
};

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

export const getDevices = async (
  quizId: string,
  to: number,
  from: number,
): Promise<[DevicesResponse | null, string?]> => {
  try {
    const devicesResponse = await makeRequest<TRequest, DevicesResponse>({
      method: "POST",
      url: `${API_URL}/${quizId}/devices`,
      withCredentials: true,
      body: { to, from },
    });

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

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

export const getGeneral = async (
  quizId: string,
  to: number,
  from: number,
): Promise<[GeneralResponse | null, string?]> => {
  try {
    const generalResponse = await makeRequest<TRequest, GeneralResponse>({
      method: "POST",
      url: `${API_URL}/${quizId}/general`,
      withCredentials: true,
      body: { to, from },
    });

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

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

export const getQuestions = async (
  quizId: string,
  to: number,
  from: number,
): Promise<[QuestionsResponse | null, string?]> => {
  try {
    const questionsResponse = await makeRequest<TRequest, QuestionsResponse>({
      method: "POST",
      url: `${API_URL}/${quizId}/questions`,
      withCredentials: true,
      body: { to, from },
    });

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

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

export const getGraphics = async (
  quizId: string,
  to: number,
  from: number,
): Promise<[GraphicsResponse | null, string?]> => {
  try {
    const questionsResponse = await makeRequest<TRequest, QuestionsResponse>({
      method: "get",
      url: `${API_URL}s/${quizId}/pipelines?from=${from}&to=${to}`,
      withCredentials: true,
    });

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

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