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

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

  return authenticationService.check().pipe(
    switchMap((authenticated) => {
      if (!authenticated) {
        const redirectURL = state.url === '/sign-out' ? '' : `redirectURL=${state.url}`;
        return of(router.parseUrl(`/auth/sign-in?${redirectURL}`));
      }

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