// reducers/initDataReducer.ts
import { REHYDRATE } from 'redux-persist';
import { INIT_DATA_FETCH_TIME } from '../actions/types';

// =======================
// Types
// =======================
export interface InitDataState {
  lastFetch: string;
}

// =======================
// Action Types
// =======================
type InitDataAction =
  | { type: typeof REHYDRATE; payload?: { initData?: InitDataState } }
  | { type: typeof INIT_DATA_FETCH_TIME; payload: string };

// =======================
// Initial State
// =======================
const initialState: InitDataState = {
  lastFetch: '',
};

// =======================
// Reducer
// =======================
export const initData = (
  state: InitDataState = initialState,
  action: InitDataAction
): InitDataState => {
  switch (action.type) {
    case REHYDRATE:
      return action.payload?.initData ?? state;

    case INIT_DATA_FETCH_TIME:
      return { ...state, lastFetch: action.payload };

    default:
      return state;
  }
};
