import { HttpInterceptorFn } from '@angular/common/http';

const TOKEN_STORAGE_KEY = 'spooty_auth_token';

export const authTokenInterceptor: HttpInterceptorFn = (req, next) => {
  let token: string | null = null;

  try {
    token = localStorage.getItem(TOKEN_STORAGE_KEY);
  } catch (error) {
    console.error('Failed to read auth token from localStorage', error);
  }

  if (!token) {
    return next(req);
  }

  return next(
    req.clone({
      setHeaders: {
        'x-spooty-token': token,
      },
    }),
  );
};
