import { inject } from '@angular/core';
import type { CanActivateFn } from '@angular/router';
import { environment } from 'environments/environment';
import { of, switchMap } from 'rxjs';
import { AuthenticationService } from '../../shared/authentication.service';

export const authorizationCodeGuard: CanActivateFn = (route, state) => {
  const authenticationService = inject(AuthenticationService);

  return authenticationService.check().pipe(
    switchMap((authenticated) => {
      if (!authenticated) {
        const redirectURL = state.url === '/sign-out' ? '' : `redirectURL=${state.url}`;
        window.location.href = `${environment.api.rest}/auth/login?${redirectURL}`;
        return of(false);
      }

      return of(true);
    }),
  );
};
