import { combineReducers, configureStore } from "@reduxjs/toolkit";
import contactReducer from "./slices/contactSlice";
import directoryReducer from "./slices/directorySlice";
import newsroomReducer from "./slices/newsroomSlice";

/**
 * To add a feature: create `slices/<name>Slice.ts` and register its reducer here.
 *
 * NOTE: `combineReducers` must stay at module scope. Redux calls `Math.random()`
 * inside it, which Next's Cache Components forbids during a component render.
 */
export const rootReducer = combineReducers({
  contact: contactReducer,
  directory: directoryReducer,
  newsroom: newsroomReducer,
});

/**
 * Store factory — a new store is created per request on the server and once
 * per browser session on the client (see StoreProvider), so state never leaks
 * between users.
 */
export const makeStore = () => configureStore({ reducer: rootReducer });

export type AppStore = ReturnType<typeof makeStore>;
export type RootState = ReturnType<typeof rootReducer>;
export type AppDispatch = AppStore["dispatch"];
