import { inject, PLATFORM_ID } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';
import { isPlatformBrowser } from '@angular/common';
import { AuthService } from '../services/auth.service';

export const sysadminOrGestorGuard: CanActivateFn = () => {
  const router = inject(Router);
  const platformId = inject(PLATFORM_ID);
  const authService = inject(AuthService);

  if (!isPlatformBrowser(platformId)) {
    // Em SSR não há storage do usuário para validar sessão/perfil.
    return true;
  }

  const token = authService.token;
  if (!token) {
    return router.parseUrl('/login');
  }

  const hasAccess = authService.hasRole('sysadmin') || authService.hasRole('gestor');
  if (!hasAccess) {
    return router.parseUrl('/dashboard');
  }

  return true;
};
