import axios, { AxiosRequestConfig } from "axios";

import {
  COLLABORATOR_API,
  HOST_API,
  PROJECT_API,
  USER_API,
  CALENDAR_API,
  GATEWAY,
} from "../config-global";

// ----------------------------------------------------------------------
// Création de la première instance Axios avec HOST_API
export const axiosInstance = axios.create({ baseURL: GATEWAY});

axiosInstance.interceptors.response.use(
  (res) => res,
  (error) =>
    Promise.reject(
      (error.response && error.response.data) || "Something went wrong"
    )
);

// axios.js

// Create an instance of axios
export const axiosInstancee = axios.create({
  baseURL: GATEWAY, // Replace with your backend base URL
});

// Add a request interceptor to add the token to headers
axiosInstancee.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem("token"); // Retrieve token from localStorage
    if (token) {
      config.headers.Authorization = `Bearer ${token}`; // Attach token to Authorization header
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

export default axiosInstancee;
// Création de la première instance Axios avec PROJECT_API
export const axiosInstance1 = axios.create({ baseURL: PROJECT_API });

axiosInstance1.interceptors.response.use(
  (res) => res,
  (error) =>
    Promise.reject(
      (error.response && error.response.data) || "Something went wrong"
    )
);
// Création de la première instance Axios avec COLLABORATOR_API
export const axiosInstance2 = axios.create({ baseURL: COLLABORATOR_API });

// Création de la première instance Axios avec USER
export const axiosInstance3 = axios.create({ baseURL: USER_API });
axiosInstance3.interceptors.response.use(
  (res) => res,
  (error) =>
    Promise.reject(
      (error.response && error.response.data) || "Something went wrong"
    )
);

axiosInstance3.interceptors.response.use(
  (res) => res,
  (error) =>
    Promise.reject(
      (error.response && error.response.data) || "Something went wrong"
    )
);

// Exported function to send a reset password request using axiosInstance
export const sendingResetPasswordAPI = async (emailData: { email: string }) => {
  try {
    const response = await axiosInstancee.post(
      "api/user/auth/resetPassword",
      emailData
    );
    return response.data;
  } catch (error: unknown) {
    const errorMessage =
      error instanceof Error ? error.message : "Unknown error occurred";
    console.error("Error:", errorMessage);
  }
};

export const verifyOtpAPI = async (otpData: {
  email: string;
  confirmationCode: string;
  operationHash: string;
}) => {
  const response = await axiosInstancee.post(
    "/api/user/auth/send-verification-code",
    otpData
  );
  return response.data;
};

// API call to update the user's password
export const updateUserPasswordAPI = async (passwordData: {
  email: string;
  password: string;
  operationHash: string;
}) => {
  try {
    const response = await axiosInstancee.post(
      "api/user/auth/updatePassword",
      passwordData
    );
    return response.data; // Assuming your backend sends a response with success
  } catch (error: unknown) {
    const errorMessage =
      error instanceof Error ? error.message : "Unknown error occurred";
    console.error("Error:", errorMessage);
  }
};
// ----------------------------------------------------------------------
// Définition de la fonction fetcher pour axiosInstance
export const fetcher = async (args: string | [string, AxiosRequestConfig]) => {
  const [url, config] = Array.isArray(args) ? args : [args];

  const res = await axiosInstance.get(url, { ...config });

  return res.data;
};
// Définition de la fonction fetcher pour axiosInstance1
export const fetcher1 = async (args: string | [string, AxiosRequestConfig]) => {
  const [url, config] = Array.isArray(args) ? args : [args];

  const res = await axiosInstance1.get(url, { ...config });

  return res.data;
};

export const fetcher2 = async (args: string | [string, AxiosRequestConfig]) => {
  const [url, config] = Array.isArray(args) ? args : [args];

  const res = await axiosInstance1.get(url, { ...config });

  return res.data;
};

// ----------------------------------------------------------------------
// Définition des endpoints pour les différentes APIs
export const endpoints = {
  chat: "/api/chat",
  projectRoute: "/api/projects",
    kanban: {
    getAllKanbanColumns: "/api/projects/api/kanban-columns",
    getKanbanColumn: (id: number) => `/api/projects/api/kanban-columns/${id}`,
    getAllKanbanColumnNames: "/api/projects/api/kanban-columns/names", 
    updateKanbanColumn: (id: number) => `api/projects/api/kanban-columns/${id}`,
    deleteKanbanColumn: (id: number) => `/api/projects/api/kanban-columns/${id}`,
    reorderColumns: "api/projects/api/kanban-columns/reorder",
    changeTaskStatus: (taskId: number, newColumnId: number) => `/api/projects/api/kanban-columns/tasks/${taskId}/move/${newColumnId}`,

    changeAllTasksStatus: "/api/projectsapi/kanban-columns/tasks/status"
  },
  calendar: {
    getAll: GATEWAY + "/api/calendar/events",
    add: GATEWAY + "/api/calendar/create",
    update: GATEWAY + "/api/calendar/update",
    delete: GATEWAY + "/api/calendar/delete",
  },
  recurrent: {
    add: GATEWAY + "/api/calendar/recurrent/create",
    update : GATEWAY + "/api/calendar/recurrent/update"
  },
  project: {
    add: PROJECT_API + "/api/projects/add",
    list: PROJECT_API + "/api/projects",
    archive: PROJECT_API + "/api/projects/archive",
    archiveList: PROJECT_API + "/api/projects/archive/all",
    delete: PROJECT_API + "/api/projects/delete",
    deleteList: PROJECT_API + "/api/projects/delete/all",
    recover: PROJECT_API + "/api/projects/recover",
    recoverList: PROJECT_API + "/api/projects/recover/all",
    favorit: PROJECT_API + "/api/projects/favorite",
    favoritList: PROJECT_API + "/api/projects/favorite/all",
    unfavorit: PROJECT_API + "/api/projects/unfavorite",
    unfavoritList: PROJECT_API + "/api/projects/unfavorite/all",
    get: PROJECT_API + "/api/projects/get",
    update: PROJECT_API + "/api/projects/update",
    addcollaborator: PROJECT_API + "/api/projects/collaborators",
    tasks: PROJECT_API + "/api/projects/tasks",
    collaboratorOfProject: GATEWAY + "/api/projects/collaborators",
    collaborator: PROJECT_API + "/api/projects/collaborator",
  },
  task: {
    add: PROJECT_API + "/api/projects/api/tasks/add",
    list: (agencyId: any, state: any) =>
      `${PROJECT_API}/api/projects/api/tasks/${agencyId}/${state}`,
    get: PROJECT_API + "/api/projects/api/tasks",
    archive: PROJECT_API + "/api/projects/api/tasks/archive",
    recover: PROJECT_API + "/api/projects/api/tasks/recover",
    delete: PROJECT_API + "/api/projects/api/tasks/delete",
    favorite: PROJECT_API + "/api/projects/api/tasks/favorite",
    unfavorit: PROJECT_API + "/api/projects/api/tasks/unfavorite",
    subTask: PROJECT_API + "/api/projects/subtasks",
    update: PROJECT_API + "/api/projects/api/tasks/update",
    status: PROJECT_API + "/projects",
  },

  collaborator: {
    list: COLLABORATOR_API + "/agency",
  },
  user: {
    getByEmail: (email: string) => `api/user/getByEmail/${email}`,
    changingLogingActivity: "api/user/changeLoginActivity",
    group: "/api/user/groups",
    user: "/api/user",
    getById: (id: string | number) => `/api/user/agency/${id}`,
    searchByEmailOrName:`/api/user/search`
  },
  comment: {
    list: PROJECT_API + "/api/projects/api/comments",
    reply: PROJECT_API + "/api/projects/api/comments/reply",
    replyCommentList: PROJECT_API + "/api/projects/api/comments/replyOfComment",
    toggleLike: PROJECT_API + "/api/projects/api/comments/toggleLike",
    deleteReply:
      PROJECT_API + "/api/projects/api/comments/delete-reply-comment",
  },

  auth: {
    me: "/api/user/auth/me",
    login: "/api/user/auth/signin",
    register: "/api/user/auth/signup",
  },
  mail: {
    list: "/api/mail/list",
    details: "/api/mail/details",
    labels: "/api/mail/labels",
  },
  post: {
    list: "/api/post/list",
    details: "/api/post/details",
    latest: "/api/post/latest",
    search: "/api/post/search",
  },
  // product: {
  //   list: '/api/product/list',
  //   details: '/api/product/details',
  //   search: '/api/product/search',
  // },
  notification: {
    startInvoiceNotification: () =>
      `/api/invoice/notify/createInvoiceNotification`,
    sendNotificationToUserAfterUpdateInvoice: () =>
      `/api/invoice/notify/updateInvoiceNotification`,
    sendNotificationToUserAfterDeleteInvoice: () =>
      `/api/invoice/notify/deleteInvoiceNotification`,
    assignTaskNotification: () => `/api/projects/notify/AssigningTaskNotification`,
    changeTaskStatusNotification: () => `/api/projects/notify/ChangingTaskStatus`,
    commentNotification: () => `/api/projects/notify/CommentNotification`,
    getNotifications: () => '/mc-notify/notifications',
    getNotificationsByEmail: (email: string) => `/mc-notify/email/${email}`,
  },

  payment_mode: {
    add: "/api/invoice/paymentMode/add",
    list: "/api/invoice/paymentMode/details/agencyId",
  },
  invoice_client: {
    add: "/api/invoice/invoiceClient/add",
    list: "/api/invoice/invoiceClient/all",
  },
  product: {
    add: "/api/invoice/product/add",
    list: "/api/invoice/product/details/agencyId",
  },
  signature: {
    upload: "/api/invoice/file/upload",
    delete: "/api/invoice/file/delete",
    download: "/api/invoice/file/download",
  },
  agencyManager: {
    findByAgencyId: "/api/invoice/invoiceClient/details/agencyId",
    findById: "/api/invoice/invoiceClient/details/Id",
    findManagersById: "/api/invoice",
  },
  invoice: {
    add: "/api/invoice/add",
    list: "/api/invoice/agencyId",
    delete: "/api/invoice/delete",
    delete_list: "/api/invoice/delete/list",
    details: "/api/invoice/details",
    update: "/api/invoice/update",
    analytic: "/api/invoice/analytics",
  },
};

//--------------------------------------------------------------------------------------------------
