// reducers/securityReducer.ts
import { REHYDRATE } from "redux-persist";
import {
    AUTHENTICATION_FAILED,
    AUTHENTICATION_REQUEST,
    AUTHENTICATION_SUCCESS,
} from "../actions/types";

// =======================
// Types
// =======================
export interface UserInfoState {
  userInfo: Record<string, any>;
  loading: boolean;
  error: Record<string, any>;
  failedCount: number;
  refreshing: boolean;
  refreshTokenPromise?: Promise<any>;
}

// Action types
type UserInfoAction =
  | { type: typeof REHYDRATE; payload?: { userInfo?: UserInfoState } }
  | { type: typeof AUTHENTICATION_REQUEST; payload: Record<string, any> }
  | { type: typeof AUTHENTICATION_SUCCESS; payload: Record<string, any> }
  | { type: typeof AUTHENTICATION_FAILED; payload: Record<string, any> }
  | { type: "AUTHENTICATION_FAILED_COUNT"; payload: number }
  | { type: "AUTHENTICATION_REFRESH"; payload: boolean }
  | { type: "REFRESH_TOKEN_PROMISE"; refreshTokenPromise: Promise<any> };

// =======================
// Initial State
// =======================
const initialState: UserInfoState = {
  userInfo: {},
  loading: false,
  error: {},
  failedCount: 0,
  refreshing: false,
};

// =======================
// Reducer
// =======================
export default function userInfoReducer(
  state: UserInfoState = initialState,
  action: UserInfoAction
): UserInfoState {
  switch (action.type) {
    case REHYDRATE:
      return action.payload?.userInfo
        ? { ...action.payload.userInfo, loading: false, error: {} }
        : initialState;

    case AUTHENTICATION_REQUEST:
      return {
        ...state,
        userInfo: action.payload,
        loading: true,
        error: {},
      };

    case AUTHENTICATION_SUCCESS:
      return {
        ...state,
        userInfo: { ...action.payload },
        loading: false,
        error: {},
      };

    case AUTHENTICATION_FAILED:
      return {
        ...state,
        userInfo: {},
        loading: false,
        error: action.payload,
      };

    case "AUTHENTICATION_FAILED_COUNT":
      return {
        ...state,
        failedCount: action.payload === 1 ? state.failedCount + 1 : 0,
        loading: false,
      };

    case "AUTHENTICATION_REFRESH":
      return {
        ...state,
        refreshing: action.payload,
        loading: false,
      };

    case "REFRESH_TOKEN_PROMISE":
      return {
        ...state,
        refreshTokenPromise: action.refreshTokenPromise,
        loading: false,
      };

    default:
      return state;
  }
}
