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

export const authInterceptor: HttpInterceptorFn = (req, next) => {
  const token = localStorage.getItem('token');

  const isProtectedEndpoint =
    req.url.includes('/api/account/me') ||
    req.url.includes('/api/account/bots') ||
    req.url.includes('/api/account/official-bots') ||
    req.url.includes('/api/board/game') ||
    req.url.includes('/api/challenge') ||
    req.url.includes('/api/tournament') ||
    req.url.includes('/api/bots');

  if (token && isProtectedEndpoint && !req.headers.has('Authorization')) {
    req = req.clone({
      setHeaders: {
        Authorization: `Bearer ${token}`
      }
    });
  }

  return next(req);
};
