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';
import { preferencesReducer } from './preferences.slice';

configureAuthStorage('ema-backoffice', true);
// Cookies are shared across ports on localhost, so the API layer must be told
// which app it belongs to — otherwise it reads the portal's token.
configureSessionScope('ema-backoffice');

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,
    preferences: preferencesReducer,
    [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;
