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

const DEFAULT_AUTHENTICATED_REDIRECT = '/dashboards/crm';

function resolveSafeReturnUrl(returnUrl: string | null): string {
  const candidate = returnUrl?.trim();
  if (!candidate) {
    return DEFAULT_AUTHENTICATED_REDIRECT;
  }

  const lowerCandidate = candidate.toLowerCase();
  const isSafeInternal =
    candidate.startsWith('/') &&
    !candidate.startsWith('//') &&
    !lowerCandidate.includes('http://') &&
    !lowerCandidate.includes('https://');

  return isSafeInternal ? candidate : DEFAULT_AUTHENTICATED_REDIRECT;
}

export const guestGuard: CanActivateFn = (route) => {
  const authService = inject(AuthService);
  const tokenStorage = inject(TokenStorageService);
  const router = inject(Router);

  const targetUrl = resolveSafeReturnUrl(route.queryParamMap.get('returnUrl'));
  const targetUrlTree = router.createUrlTree([targetUrl]);

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

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

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

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