import { Customer } from '@agiliza/api/domain'
import { types as loginTypes } from '@agiliza/redux/ui/login'
import { types as authenticationTypes } from '@agiliza/redux/useCases/authentication'
import { createSlice, PayloadAction } from '@reduxjs/toolkit'

export interface State {
  initializing: boolean
  authenticating: boolean
  authenticated: boolean
  error?: string
  customer?: Customer
}

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

const session = createSlice({
  name: 'session',
  initialState,
  reducers: {},
  extraReducers: {
    [loginTypes.login.fulfilled]: (state, action: PayloadAction<Customer>) => {
      state.authenticated = true
      state.customer = action.payload
      console.log(action.payload)
    },
    [loginTypes.logout.fulfilled]: (state) => {
      state.authenticated = false
    },
    [loginTypes.connect.fulfilled]: (state) => {
      state.authenticated = true
    },
    // [authenticationTypes.createCustomer.fulfilled]: (state, action: PayloadAction<Customer>) => {
    //   state.customer = action.payload
    // },
    [authenticationTypes.getLoggedCustomer.fulfilled]: (state, action: PayloadAction<Customer>) => {
      state.customer = action.payload
    },
  },
})

export default session
