import { inject } from '@angular/core';
import { CanActivateChildFn, Router } from '@angular/router';
import { catchError, map, of } from 'rxjs';
import { AuthService } from '../auth/auth.service';
import { TokenStorageService } from '../auth/token-storage.service';

export const authGuard: CanActivateChildFn = (_childRoute, state) => {
  const authService = inject(AuthService);
  const tokenStorage = inject(TokenStorageService);
  const router = inject(Router);

  const loginUrlTree = router.createUrlTree(['/auth/login'], {
    queryParams: { returnUrl: state.url },
  });

  if (!authService.accessToken || !authService.currentUser) {
    authService.logout();
    return loginUrlTree;
  }

  if (!tokenStorage.isAccessTokenExpired()) {
    return true;
  }

  if (!authService.refreshToken || tokenStorage.isRefreshTokenExpired()) {
    authService.logout();
    return loginUrlTree;
  }

  return authService.refreshAccessToken().pipe(
    map(() => true),
    catchError(() => {
      authService.logout();
      return of(loginUrlTree);
    })
  );
};
