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

export const noAuthenticationGuard: CanActivateFn | CanActivateChildFn = (route, state) => {
  const router: Router = inject(Router);
  const authenticationService: AuthenticationService = inject(AuthenticationService);

  // Check the authentication status
  return authenticationService.check().pipe(
    switchMap((authenticated) => {
      // If the user is authenticated...
      if (authenticated) {
        // Allow access if this is an OAuth SSO continue flow
        // The sign-in component needs to process the continue param
        if (route.queryParamMap.has('continue')) {
          return of(true);
        }

        return of(router.parseUrl(''));
      }

      // Allow the access
      return of(true);
    }),
  );
};
