import { HttpInterceptorFn } from "@angular/common/http";
import { KeycloakService } from "keycloak-angular";
import { inject } from "@angular/core";
import { from, switchMap } from "rxjs";

export const tokenInterceptor: HttpInterceptorFn = (req, next) => {
  const keycloak = inject(KeycloakService);

  if (!keycloak.isLoggedIn()) {
    return next(req);
  }

  if (keycloak.isTokenExpired()) {
    keycloak.updateToken().then();
  }

  return from(keycloak.getToken()).pipe(
    switchMap((token) => {
      const modifiedReq = token
        ? req.clone({
            headers: req.headers.set("Authorization", `Bearer ${token}`),
          })
        : req;

      return next(modifiedReq);
    }),
  );
};
