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

import { getInventoryVariables } from './thunks';
import type { InventoryMapping } from './types';

export interface InventoryState {
  error: string | null;
  // Set only on a successful fetch, so it distinguishes "not fetched yet" and
  // "failed" from "fetched, no attributes reported".
  loaded: boolean;
  loading: boolean;
  // CFE_mapping: available inventory attributes keyed by label.
  mapping: InventoryMapping;
}

const initialState: InventoryState = {
  mapping: {},
  loading: false,
  loaded: false,
  error: null
};

const inventorySlice = createSlice({
  name: 'inventory',
  initialState,
  reducers: {},
  extraReducers: builder => {
    builder
      .addCase(getInventoryVariables.pending, state => {
        state.loading = true;
        state.error = null;
      })
      .addCase(getInventoryVariables.fulfilled, (state, { payload }) => {
        state.loading = false;
        state.loaded = true;
        state.mapping = payload;
      })
      .addCase(getInventoryVariables.rejected, state => {
        state.loading = false;
        state.error = 'Failed to load inventory attributes.';
      });
  }
});

export type { CfeAttribute, InventoryMapping, AttributeType } from './types';
export { getInventoryVariables };
export default inventorySlice.reducer;
