import axios from "axios";
import { useAuthStore } from "@/store/authStore";
import { useLanguageStore } from "@/store/languageStore";
import { useBanNoticeStore } from "@/store/banNoticeStore";
import { API_BASE_URL } from "@/lib/api/config";
import { normalizeDigitsDeep } from "@/lib/digits";

const apiClient = axios.create({
  baseURL: API_BASE_URL,
});

apiClient.interceptors.request.use(
  (config) => {
    // Get token and language from Zustand stores
    const token = useAuthStore.getState().user?.auth_token;
    const language = useLanguageStore.getState().language || "en";

    if (token) {
      config.headers.Authorization = `Token ${token}`;
    }
    config.headers["x-lang"] = language;
    config.headers["Accept-Language"] = language;
    // The social-auth endpoints localize their messages from `Lang`.
    config.headers["Lang"] = language;

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

/**
 * Only 401 means "this token is no longer a session". The API answers an
 * authenticated-but-not-permitted request with 403 — "Only organizations can
 * create events.", "You can only update your own events.", "Only the event
 * organizer can view all registrations." and ~60 more — so logging out on 403
 * ejected a perfectly valid session whenever the user hit a permission wall.
 * A missing or expired token is a 401 from `Authenticate::unauthenticated()`;
 * nothing in the API returns 403 for a credential problem.
 *
 * **BE-129 — `endSession()`, not `logout()`.** A 401 says *this* token is
 * dead; it says nothing about the other accounts signed in on this device, and
 * `logout()` would throw them away too. It also does not promote one of them:
 * continuing silently as somebody else would mean the reader's next action — a
 * comment, a registration, a withdrawal — is taken by an account they never
 * chose. The session ends, the others stay, and the sign-in screen offers them.
 */
apiClient.interceptors.response.use(
  (response) => {
    // Digits do not follow the UI language in this product: an Arabic session
    // still renders `12345`, never `١٢٣٤٥`. The API disagrees — `ar_num()`
    // rewrites every numeric field into Arabic-Indic digits when the language
    // header is `ar`, and hands them over as strings. Normalizing once here
    // means no render site has to think about it, and arithmetic on a count
    // (`> 0`, sums, sorts) works instead of yielding NaN.
    response.data = normalizeDigitsDeep(response.data);
    // A rejected business operation can arrive with HTTP 200. Keep it on the
    // error path for every query/mutation, including callers without a local
    // envelope check, and preserve field errors for the visible form.
    const body = response.data;
    if (body && typeof body === "object" && (body.key === "fail" || body.response_status?.error === true)) {
      if (body.data?.error_code === "user_banned" && typeof body.msg === "string") {
        useBanNoticeStore.getState().show(body.msg, body.data);
      }
      throw new axios.AxiosError(body.msg || "Request failed", "ERR_API_RESPONSE", response.config, response.request, response);
    }
    return response;
  },
  (error) => {
    // A banned account (2026-10-19): sign-in answers 403, any request with
    // its token 401 — both with `data.error_code: "user_banned"` and the
    // popup's text in `msg`. Open the popup before the 401 ends the session.
    const body = error?.response?.data;
    if (body?.data?.error_code === "user_banned" && typeof body.msg === "string") {
      useBanNoticeStore.getState().show(body.msg, body.data);
    }
    /*
     * BE-160 — except `/social-auth/`. Its 401 means the Google ID token /
     * LinkedIn ticket was rejected, not that the session token is dead, and
     * the request may well carry a live session: adding a second account
     * (BE-129) signs in while another one is active. Ending that session over
     * a stale social credential would sign the reader out of an account the
     * failure says nothing about.
     */
    const isSocialCredentialFailure = /\/social-auth\/?$/.test(
      String(error?.config?.url ?? "")
    );
    if (error?.response?.status === 401 && !isSocialCredentialFailure) {
      // A request can finish after sign-out or switching accounts. Only end
      // the session whose token was rejected, never the newly active account.
      const session = useAuthStore.getState();
      const requestAuthorization = error.config?.headers?.Authorization;
      if (session.user?.auth_token && requestAuthorization === `Token ${session.user.auth_token}`) {
        session.endSession();
      }
    }
    // Validation messages and field errors are localized too, and are read
    // through lib/api/errors.ts — normalize them on the same terms.
    if (error?.response?.data !== undefined) {
      error.response.data = normalizeDigitsDeep(error.response.data);
    }
    return Promise.reject(error);
  }
);

export default apiClient;
