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 sysadminOnlyGuard: CanActivateFn = () => {
  const router = inject(Router);
  const platformId = inject(PLATFORM_ID);
  const authService = inject(AuthService);

  if (!isPlatformBrowser(platformId)) {
    return true;
  }

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

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

  return true;
};
