export type TResourcePhase = 'idle' | 'loading' | 'refreshing' | 'ready' | 'stale' | 'error';

export interface IResourceState {
  phase: TResourcePhase;
  error: string | null;
  lastSuccessAt: number | null;
}

export const createIdleResourceState = (): IResourceState => ({
  phase: 'idle',
  error: null,
  lastSuccessAt: null,
});

export const startResourceLoad = (
  previousArg: IResourceState,
  hasValueArg: boolean,
): IResourceState => ({
  ...previousArg,
  phase: hasValueArg ? 'refreshing' : 'loading',
  error: null,
});

export const completeResourceLoad = (completedAtArg = Date.now()): IResourceState => ({
  phase: 'ready',
  error: null,
  lastSuccessAt: completedAtArg,
});

export const failResourceLoad = (
  previousArg: IResourceState,
  hasValueArg: boolean,
  errorArg: string,
): IResourceState => ({
  ...previousArg,
  phase: hasValueArg ? 'stale' : 'error',
  error: errorArg,
});
