"use client";
import axios, { IApiResponse, IApiError } from "axios";
import { AxiosError } from "axios";
import { ApiEndpoint } from "@/lib/services/api.service";
import { makeUseAxios } from "axios-hooks";
import { getAuthToken, handleAuthLogout } from "./auth.service";
import { AuthTokenType } from "../interfaces/auth/auth.interface";
import { apiCache } from "./cache.service";
import { i18n } from "@/i18n/i18n";
import { getPlatformServices } from "@/lib/platform/services";

declare module "axios" {
  export interface AxiosRequestConfig {
    useCache?: boolean
    cacheTTL?: number
  }
}

// A request that gets no answer in this time fails with "api:timeout-error"
// (screens then offer a retry) instead of leaving a spinner up.
export const API_TIMEOUT_MS = 20000;

const instance = axios.create({
  baseURL: ApiEndpoint('main', 'base'),
  timeout: API_TIMEOUT_MS
});

instance.interceptors.request.use((config) => {
  const token = getAuthToken(AuthTokenType.ACCESS);
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }

  // App platform, store and version for the backend (none on the website).
  for (const [name, value] of Object.entries(getPlatformServices().requestHeaders())) {
    config.headers.set(name, value);
  }

  if (config.method === "get" && config.useCache) {
    const cached = apiCache.get(config.url!, config.params);
    if (cached) {
      return Promise.reject({
        __fromCache: true,
        data: cached
      });
    }
  }

  return config;
}, (error) => {
  return Promise.reject(error);
});

instance.interceptors.response.use(
  (response) => {
    response.body = response.data;

    const { config } = response;

    if (config.method === "get" && config.useCache) {
      apiCache.set(
        config.url!,
        config.params,
        response.data,
        config.cacheTTL || 60000
      );
    }

    return response;
  },
  (error: AxiosError<IApiResponse<any>>) => {

    if ((error as any).__fromCache) {
      return Promise.resolve({
        data: (error as any).data,
        body: (error as any).data
      });
    }

    let apiError: IApiError;

    if (!error.response) {
      const offline = typeof navigator !== "undefined" && navigator.onLine === false;
      const timedOut = error.code === "ECONNABORTED" || error.code === "ETIMEDOUT";
      const message = offline || error.code === "ERR_NETWORK"
        ? "api:internet-error"
        : timedOut
          ? "api:timeout-error"
          : "api:internal-error";

      apiError = {
        ok: false,
        msg: message,
        httpStatus: 500
      };
    } else {
      apiError = {
        ok: false,
        msg: error.response.data?.msg ?? "api:internal-error",
        data: error.response.data?.data,
        httpStatus: error.response.status
      };
    }

    if (apiError.httpStatus == 401) {
      handleAuthLogout();
      if (typeof window !== "undefined") {
        const currentPath = window.location.pathname;
        if (!currentPath.startsWith("/auth/login")) {
          setTimeout(() => {
            window.location.href = "/auth/login";
          }, 1000);
        }
      }
      return Promise.reject(apiError);
    }

    return Promise.reject(apiError);
  }
);

export const useApi = makeUseAxios({
  axios: instance,
  defaultOptions: { manual: true, useCache: false, autoCancel: false }
});

/** No answer at all (offline, unreachable, timed out), as opposed to an error the server returned. */
export function isConnectionError(error: unknown): boolean {
  const msg = typeof error === "object" && error && "msg" in error ? (error as { msg?: string }).msg : undefined;
  return msg === "api:internet-error" || msg === "api:timeout-error";
}

export function getApiErrorMessage(error: unknown): string {
  if (typeof error === "object" && error && "msg" in error) {
    return i18n((error as any).msg);
  }

  return i18n("api:internal-error");
}
