import { DOMAIN, TOKEN } from "@/constants";
import { showErrorToast } from "@/services/toast_service";
import { getStorageItem } from "@/utils/storage";
import axios, { AxiosInstance } from "axios";
import { handle401 } from "./auth";

const codeMessage = {
  200: "The server successfully returned the requested data。",
  201: "New or modified data succeeded。",
  202: "A request has been queued in the background (asynchronous task)。",
  204: "Data deleted successfully。",
  400: "There is an error in the request sent, the server did not perform the operation of creating or modifying data。",
  401: "The user does not have permission (token, username, password is wrong) 。",
  403: "User is authorized, but access is prohibited。",
  404: "The request issued was for a non-existent record, the server did not operate。",
  406: "The requested format is not available。",
  410: "The requested resource is permanently deleted and will no longer be available。",
  422: "When creating an object, a validation error occurred。",
  500: "Server error, please check the server。",
  502: "Gateway error。",
  503: "Service unavailable, server temporarily overloaded or maintained。",
  504: "Gateway timeout。",
};

// Tạo instance axios với cấu hình cơ bản
const api: AxiosInstance = axios.create({
  baseURL: "https://sgw.gms.vn",
  timeout: 20000, // Timeout 20 giây
  headers: {
    "Content-Type": "application/json",
  },
});

console.log("🚀 Axios baseURL:", api.defaults.baseURL);

// Interceptor cho request (thêm token nếu cần)
api.interceptors.request.use(
  async (config) => {
    // Thêm auth token nếu có
    const token = await getStorageItem(TOKEN);
    if (token) {
      config.headers.Authorization = `${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// Interceptor cho response (xử lý lỗi chung)
api.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    if (!error.response) {
      const networkErrorMsg =
        error.message || "Network error - please check connection";
      showErrorToast("Lỗi kết nối");
      console.error("Response Network Error: ", networkErrorMsg);

      return Promise.reject(error);
    }

    const { status, statusText, data } = error.response;

    // Ưu tiên: codeMessage → backend message → statusText
    const errMsg =
      codeMessage[status as keyof typeof codeMessage] ||
      data?.message ||
      statusText ||
      "Unknown error";

    // Không hiển thị toast cho status 400 (validation errors) và 404 (not found)
    // 404 được xử lý riêng bởi component (ví dụ: search crew không tìm thấy)
    if (status !== 400 && status !== 404) {
      showErrorToast(`Lỗi ${status}: ${errMsg}`);
    }

    if (status === 401) {
      handle401();
    }
    return Promise.reject(error);
  }
);

export default api;
