import { configureStore } from "@reduxjs/toolkit";
import {
  baseApi,
  configureSessionScope,
  configureTokenRefresh,
} from "@ema-platform/api";
import {
  authReducer,
  signupReducer,
  configureAuthStorage,
  authStorage,
  refreshAccessToken,
  logout,
  setToken,
} from "@ema-platform/auth";
import type { AuthUser, CurrentProfile } from "@ema-platform/auth";

configureAuthStorage("ema-portal", true);
// See the backoffice store: cookies ignore the port, so the API layer is told
// which app it is rather than guessing from a shared jar.
configureSessionScope("ema-portal");

// Dev-only preview mode (VITE_USE_MOCKS=true): seed a fake session so
// ProtectedRoute (which only checks that a token exists) treats the user as
// logged in without a real backend to authenticate against. Only runs when
// no real session is already present, so a genuine login is never clobbered.
if (
  (import.meta as { env?: Record<string, string> }).env?.["VITE_USE_MOCKS"] === "true" &&
  !authStorage.getToken()
) {
  authStorage.setToken("mock-dev-token");
  authStorage.setRefreshToken("mock-dev-refresh-token");
  authStorage.setUser<AuthUser>({
    id: "user-mock-001",
    email: "abebe.tesfaye@example.et",
    username: "abebe.tesfaye",
    phoneNumber: "+251911223344",
    name: { am: "አበበ ተስፋዬ", en: "Abebe Tesfaye" },
    status: "ACTIVE",
    sharepointId: null,
    hasSetPassword: true,
    hasFinishedRegistration: true,
    hasFinishedDMSOnboarding: true,
    isPhoneNumberVerified: true,
    userType: "PORTAL",
  });
}

const preloadedAuth = (() => {
  const token = authStorage.getToken();
  const user = authStorage.getUser<AuthUser>();
  const profile = authStorage.getProfile<CurrentProfile>();
  if (token && user) {
    return {
      token,
      user,
      isAuthenticated: true,
      currentProfile: profile ?? null,
    };
  }
  return undefined;
})();

export const store = configureStore({
  reducer: {
    auth: authReducer,
    signup: signupReducer,
    [baseApi.reducerPath]: baseApi.reducer,
  },
  preloadedState: preloadedAuth ? { auth: preloadedAuth } : undefined,
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware().concat(baseApi.middleware),
});

configureTokenRefresh({
  onTokenExpired: async () => {
    const token = await refreshAccessToken();

    store.dispatch(setToken(token));

    return token;
  },

  onAuthFailure: () => {
    store.dispatch(logout());
    window.location.href = "/";
  },
});

export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;
