import { API_RESPONSE } from "@/types/interfaces";
import axios, { AxiosResponse, InternalAxiosRequestConfig } from "axios";
import Cookies from "js-cookie"; 
import { deviceInformation } from "./deviceInfo";
// import { handleApiErrors } from './global';

// declare module 'axios' {
//   export interface AxiosRequestConfig {
//     // url: string;
//     // method: string;
//   }
// }
axios.interceptors.request.use(
  (config: InternalAxiosRequestConfig<unknown>) => {
    if (typeof window !== "undefined") {
      document.body.style.pointerEvents = "none";
    }
    return config;
  },
  (error: unknown) =>
    // Do something with request error
    Promise.reject(error)
);

axios.interceptors.response.use(
  (response: AxiosResponse<unknown, unknown>) => {
    if (typeof window !== "undefined") {
      document.body.style.pointerEvents = "auto";
    }
    return response;
  },
  (error: unknown) => Promise.reject(error)
);

interface API {
  (
    url: string,
    method?: string,
    options?: {
      data?: unknown;
      signal?: AbortSignal;
      params?: unknown;
      paramsSerializer?: unknown;
      responseType?: string;
      token?: string;
      headers?: {
        Id?: string;
        type?: string;
        Type?: string;
        language?: string;
        "Content-Type"?: string;
        Authorization?: string;
        ip_address?: string;
        platform?: string;
        browser?: string;
        isMobile?: string;
        sessionId?: string;
        smstype?: number;
        emailtype?: number;
      };
    }
  ): void;
}

interface AxiosRequestConfig {
  url: string;
  method: string;
  data?: unknown;
  signal?: AbortSignal;
  timeout?: number;
  headers?: {
    language?: string;
    "Content-Type"?: string;
    Authorization?: string;
    ip_address?: string;
    platform?: string;
    browser?: string;
    isMobile?: string;
    sessionId?: string;
    type?: string;
  };
}

let deviceInfo = null;
export const api: API = async (url, method = "GET", options = {}) => {
  if (deviceInfo === null) {
    deviceInfo = await deviceInformation();
  }
  const lang = Cookies.get("lang") || "en";
  const token = Cookies.get("accessToken") ?? ""
  let config: AxiosRequestConfig = {
    url,
    method: method || "GET",
    timeout: 30000,
    signal: options.signal as AbortSignal
  };

  if (options.headers) {
    config = { ...config, headers: { ...options.headers } };
  }

  options["headers"] = {
    "Content-Type": "application/json",
    language: lang as string,
    ...(token && { Authorization: `Bearer ${token}` }),
    ...options.headers
  };
  if (deviceInfo) {
    options.headers["ip-address"] = deviceInfo?.ip_address;
    options.headers["platform"] = deviceInfo?.platform;
    options.headers["browser"] = deviceInfo?.browser;
    options.headers["isMobile"] = deviceInfo?.isMobile;
  }

  config = { ...config, ...options };
  try {
    const resp = await axios(config);
    return resp.data as API_RESPONSE;
  } catch (e) {
    if (typeof window !== "undefined") {
      document.body.style.pointerEvents = "auto";
    }
    if (e?.response?.data) {
      if (e.response.status === 504) {
        console.error("API services are currently Offline", "warning");
      }
      throw e.response.data;
      return { status: false, ...e.response.data };
    }
  }
};
