/**
 * Type-safe session storage management for authentication flows
 */

export const SessionFlags = {
  MFA_STEP_UP_REQUIRED: 'mfa_step_up_required',
  MFA_INTENDED_PATH: 'mfa_intended_path',
  MFA_CHALLENGE_ID: 'mfa_challenge_id',
  AUTH_METHOD: 'auth_method',
} as const;

export type SessionFlagKey = typeof SessionFlags[keyof typeof SessionFlags];

/**
 * Set the MFA step-up required flag
 */
export function setStepUpRequired(required: boolean, intendedPath?: string): void {
  if (required) {
    sessionStorage.setItem(SessionFlags.MFA_STEP_UP_REQUIRED, 'true');
    if (intendedPath) {
      sessionStorage.setItem(SessionFlags.MFA_INTENDED_PATH, intendedPath);
    }
  } else {
    clearStepUpFlags();
  }
}

/**
 * Check if MFA step-up is required
 */
export function getStepUpRequired(): boolean {
  return sessionStorage.getItem(SessionFlags.MFA_STEP_UP_REQUIRED) === 'true';
}

/**
 * Get the intended path after MFA verification
 */
export function getIntendedPath(): string {
  return sessionStorage.getItem(SessionFlags.MFA_INTENDED_PATH) || '/';
}

/**
 * Clear all MFA step-up flags
 */
export function clearStepUpFlags(): void {
  sessionStorage.removeItem(SessionFlags.MFA_STEP_UP_REQUIRED);
  sessionStorage.removeItem(SessionFlags.MFA_INTENDED_PATH);
  sessionStorage.removeItem(SessionFlags.MFA_CHALLENGE_ID);
}

/**
 * Store the authentication method used
 */
export function setAuthMethod(method: 'password' | 'oauth' | 'magiclink'): void {
  sessionStorage.setItem(SessionFlags.AUTH_METHOD, method);
}

/**
 * Get the authentication method used
 */
export function getAuthMethod(): 'password' | 'oauth' | 'magiclink' | null {
  const method = sessionStorage.getItem(SessionFlags.AUTH_METHOD);
  if (method === 'password' || method === 'oauth' || method === 'magiclink') {
    return method;
  }
  return null;
}

/**
 * Clear the authentication method
 */
export function clearAuthMethod(): void {
  sessionStorage.removeItem(SessionFlags.AUTH_METHOD);
}

/**
 * Clear all authentication-related session flags
 */
export function clearAllAuthFlags(): void {
  Object.values(SessionFlags).forEach(flag => {
    sessionStorage.removeItem(flag);
  });
}
