import * as ActionTypes from '../actionTypes'
import { AuthDispatchTypes, AuthState } from './types'

const initialState: AuthState = {
  loggedIn: false
}

const reducer = (
  state = initialState,
  action: AuthDispatchTypes
): AuthState => {
  switch (action.type) {
    case ActionTypes.SET_AUTH_STATE: {
      const { loginMethod, nostrLoginAuthMethod, keyPair } = state

      return {
        loginMethod,
        nostrLoginAuthMethod,
        keyPair,
        ...action.payload
      }
    }
    case ActionTypes.UPDATE_LOGIN_METHOD: {
      const { payload } = action

      return {
        ...state,
        loginMethod: payload
      }
    }

    case ActionTypes.UPDATE_NOSTR_LOGIN_AUTH_METHOD: {
      const { payload } = action

      return {
        ...state,
        nostrLoginAuthMethod: payload
      }
    }

    case ActionTypes.UPDATE_KEYPAIR: {
      const { payload } = action

      return {
        ...state,
        keyPair: payload
      }
    }

    case ActionTypes.RESTORE_STATE:
      return action.payload.auth || initialState

    default:
      return state
  }
}

export default reducer
