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

const initialState: AuthState = {
  loggedIn: false
}

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

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

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

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

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

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

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

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

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

    case ActionTypes.RESTORE_STATE:
      return action.payload.auth

    default:
      return state
  }
}

export default reducer
