import { ProposalDataContextRepositoryImplFactory } from '@agiliza/api/useCases'
import { appPlatform } from '@agiliza/constants/platform'
import { createAsyncReducers, getTypesThunkActions, values } from '@agiliza/utils/method'
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'

const prefix = 'useCases/proposalData'

export interface State {
  fetching: boolean
}

export const initialState: State = {
  fetching: false,
}

export const actions = {
  fetchContext: createAsyncThunk(`${prefix}/fetchContext`, async (_, thunkApi) => {
    const useCase = ProposalDataContextRepositoryImplFactory.create(appPlatform)
    try {
      return await useCase.fetchContext()
    } catch (e) {
      return thunkApi.rejectWithValue(e)
    }
  }),
} as const
export const types = getTypesThunkActions(actions)

const login = createSlice({
  name: prefix,
  initialState,
  reducers: {},
  extraReducers: {
    ...values(types).reduce((reducers, type) => ({ ...reducers, ...createAsyncReducers(type) }), {}),
  },
})

export default login
