import $flow from "@appsflow/core";

import { AnyAction, configureStore, createSlice, EnhancedStore, PayloadAction } from "@reduxjs/toolkit";
import Controller from "./controller";
import { getRoutes } from "./managers/routes";

let store: EnhancedStore<any, AnyAction, any>;

// export const routesSlice = createSlice( {
//     name: "Flow/Redux/Routes",
//     initialState: {
//         current: Object,
//         history: Array<object>(),
//     },
//     reducers: {
//         set( state, action: PayloadAction<any> ) {
//             state.history.push( state.current );
//             state.current = action.payload
//         },
//     }
// } );

export function initStore( ) {
    const controllers = Object.values( $flow.managers().controllers.getAll() ).filter(
        ( controller: any ) => controller instanceof Controller
    ) as Controller[];

    const reducer: any = {},
        slices = Object.values( controllers )
            .map( ( controller ) => controller.getSlice() )
            .filter( ( x ) => !! x )

    slices.forEach( ( slice ) => {
        reducer[ slice.name ] = slice.reducer;
    } );

    // reducer[ routesSlice.name ] = routesSlice.reducer;

    store = configureStore( { reducer } )

    // @ts-ignore
    globalThis.$flow.redux = { store };

    // TODO: Find better solution.
    getRoutes();

    controllers.forEach( ( controller ) => controller.registerRoutes() );
}

export function getStore(): EnhancedStore<any, AnyAction, []> {
    return store;
}
