import { Broker, User } from '@agiliza/api/domain'
import { types as loginTypes } from '@agiliza/redux/ui/login'
import { createSlice, PayloadAction } from '@reduxjs/toolkit'

export interface State {
  initializing: boolean
  authenticating: boolean
  authenticated: boolean
  error?: string
  broker?: Broker
}

export const initialState: State = {
  authenticated: false,
  authenticating: false,
  initializing: false,
}

const session = createSlice({
  name: 'session',
  initialState,
  reducers: {},
  extraReducers: {
    [loginTypes.login.fulfilled]: (state, action: PayloadAction<User>) => {
      state.authenticated = true
    },
    [loginTypes.logout.fulfilled]: (state) => {
      state.authenticated = false
    },
    [loginTypes.connect.fulfilled]: (state, action: PayloadAction<Broker>) => {
      state.authenticated = true
      state.broker = action.payload
    },
  },
})

export default session
