import { createSlice } from '@reduxjs/toolkit';

import type { Module } from '../../types';
import { fetchCategoryModules, fetchModule, fetchModulesList } from './thunks';

export interface ModulesState {
  categories: Record<string, Module[]>;
  current: Module | null;
  list: Module[];
  loading: boolean;
  total: number;
}

const initialState: ModulesState = {
  categories: {},
  current: null,
  list: [],
  loading: false,
  total: 0
};

const modulesSlice = createSlice({
  name: 'modules',
  initialState,
  reducers: {},
  extraReducers: builder => {
    builder
      .addCase(fetchModulesList.pending, state => {
        state.loading = true;
      })
      .addCase(fetchModulesList.fulfilled, (state, { payload }) => {
        state.loading = false;
        state.list = payload.data ?? [];
        state.total = payload.meta?.total ?? 0;
      })
      .addCase(fetchModulesList.rejected, state => {
        state.loading = false;
      })
      .addCase(fetchModule.fulfilled, (state, { payload }) => {
        state.current = payload;
      })
      .addCase(fetchCategoryModules.fulfilled, (state, { payload }) => {
        state.categories[payload.category] = payload.modules;
      });
  }
});

export default modulesSlice.reducer;
