import type { BaseQueryFn, FetchArgs, FetchBaseQueryError } from "@reduxjs/toolkit/query";
import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react";
import { API_BASE_URL } from "@/lib/api-base-url";
import { clearAuthSession, getLoginRedirectPath } from "@/lib/auth";

const rawBaseQuery = fetchBaseQuery({
  baseUrl: API_BASE_URL,
  prepareHeaders: (headers) => {
    const token = typeof window !== "undefined" ? localStorage.getItem("token") : null;
    if (token) {
      headers.set("Authorization", `Bearer ${token}`);
    }
    return headers;
  },
});

const baseQueryWithAuthHandling: BaseQueryFn<string | FetchArgs, unknown, FetchBaseQueryError> = async (
  args,
  api,
  extraOptions,
) => {
  const hasToken = typeof window !== "undefined" ? Boolean(localStorage.getItem("token")) : false;
  const result = await rawBaseQuery(args, api, extraOptions);

  if (typeof window !== "undefined" && hasToken && result.error?.status === 401) {
    const redirectPath = getLoginRedirectPath();
    clearAuthSession();
    window.location.href = redirectPath;
  }

  return result;
};

export const apiSlice = createApi({
  reducerPath: "api",
  baseQuery: baseQueryWithAuthHandling,
  tagTypes: ["Registration", "Cashflow", "Analytics", "Admin", "Notification"],
  endpoints: () => ({}),
});
