'use client';

import middlewares from '@akinon/next/redux/middlewares';
import reducers from '@akinon/next/redux/reducers';
import {
  Action,
  AnyAction,
  configureStore,
  Middleware,
  Store,
  ThunkAction,
  ThunkDispatch
} from '@reduxjs/toolkit';
import categoryReducer from '@theme/redux/reducers/category';
import categoryMiddleware from '@theme/redux/middlewares/category';

// Import all action creators from akinon-next
import * as defaultActions from '@akinon/next/redux/actions';
import { rtkApiActionCreators } from '@akinon/next/redux/actions';
import * as categorySlice from './reducers/category';

const _middlewares: Middleware[] = [...middlewares, categoryMiddleware];

const _reducers = {
  ...reducers,
  category: categoryReducer
};

const actionCreators = {
  // Slice actions (automatically extracted from akinon-next)
  ...defaultActions,
  // RTK Query API endpoints from akinon-next
  ...rtkApiActionCreators,
  // Local category slice actions
  ...categorySlice
};

export const makeStore = (): Store<{
  [key in keyof typeof _reducers]: ReturnType<typeof _reducers[key]>;
}> =>
  configureStore({
    reducer: _reducers,
    middleware: (getDefaultMiddleware) =>
      getDefaultMiddleware().concat(_middlewares),
    devTools:
      process.env.NODE_ENV !== 'production'
        ? {
            actionCreators
          }
        : false
  });

export type AppStore = ReturnType<typeof makeStore>;

export type RootState = ReturnType<AppStore['getState']>;

export type TypedDispatch = ThunkDispatch<RootState, void, AnyAction>;

export type AppDispatch = AppStore['dispatch'];

export type AppThunk<ReturnType = void> = ThunkAction<
  ReturnType,
  RootState,
  unknown,
  Action<string>
>;

export const store = makeStore();
