import { HttpInterceptorFn } from '@angular/common/http';
import { KeycloakService } from 'keycloak-angular';
import { inject } from '@angular/core';
import { from, switchMap } from 'rxjs';
import { ConfigService } from 'src/app/service/config.service';
import { catchError } from 'rxjs/operators';
import { AuthService } from 'src/app/service/auth.service';

export const tokenInterceptor: HttpInterceptorFn = (req, next) => {
  const config = inject(ConfigService);
  if (
    !config.settings.api.url ||
    !req.url.startsWith(config.settings.api.url)
  ) {
    return next(req);
  }

  const keycloak = inject(KeycloakService);
  if (!keycloak.isLoggedIn()) {
    return next(req);
  }

  const auth = inject(AuthService);
  return from(keycloak.getToken()).pipe(
    switchMap(token => {
      if (!token) {
        return next(req);
      }

      if (!keycloak.isTokenExpired()) {
        return next(
          req.clone({
            headers: req.headers.set('Authorization', `Bearer ${token}`),
          })
        );
      }

      return from(keycloak.updateToken(30)).pipe(
        switchMap(() => {
          return keycloak.getToken();
        }),
        switchMap(newToken => {
          return next(
            req.clone({
              headers: req.headers.set('Authorization', `Bearer ${newToken}`),
            })
          );
        }),
        catchError(() => {
          auth.logout().then();
          return next(req);
        })
      );
    })
  );
};
