import {
  Actions,
  ActionType,
  Signin,
} from './auth.action';

import {
  State,
  initialState,
} from './auth.state';

import { Member } from '@overflow/commons-typescript/model/member';
import { DomainMember } from '@overflow/commons-typescript/model/domain';

export function reducer(state = initialState, action: Actions): State {
  switch (action.type) {
    case ActionType.Signin: {
      return {
        ...state,
        error: null,
        pending: true,
      };
    }

    case ActionType.SigninSuccess: {
      const domainMember = action.payload.domainMember;
      return {
        ...state,
        signined: true,
        error: null,
        pending: false,
        member: domainMember.member,
        domain: domainMember.domain,
      };
    }

    case ActionType.SigninFailure: {
      return {
        ...state,
        signined: false,
        error: action.payload,
        pending: false,
        member: null,
        domain: null,
      };
    }

    case ActionType.SigninCookieSuccess: {
      return {
        ...state,
        signined: true,
        error: null,
        pending: false,
        member: action.payload.member,
        domain: action.payload.domain,
      };
    }

    case ActionType.SigninCookieFailure: {
      return {
        ...state,
        signined: false,
        error: action.payload,
        pending: false,
        member: null,
        domain: null,
      };
    }


    case ActionType.Signout: {
      return {
        ...state,
        error: null,
        pending: true,
      };
    }

    case ActionType.SignoutSuccess: {
      return {
        ...state,
        signined: false,
        error: null,
        pending: false,
        member: null,
        domain: null,
      };
    }

    case ActionType.SignoutFailure: {
      return {
        ...state,
        error: action.payload,
        pending: false,
      };
    }

    default: {
      return state;
    }
  }
}
