import { inject } from '@angular/core';
import { Router, CanActivateFn } from '@angular/router';
import { AuthService, UserType } from '../services/auth.service';
import { NotificationService } from '../services/notification.service';

export const roleGuard: CanActivateFn = (route, state) => {
  const authService = inject(AuthService);
  const router = inject(Router);
  const notification = inject(NotificationService);

  const requiredRoles = route.data['roles'] as UserType[] | undefined;

  if (!requiredRoles || requiredRoles.length === 0) {
    return true;
  }

  if (authService.hasAnyRole(requiredRoles)) {
    return true;
  }

  notification.error('You do not have permission to access this page.');
  router.navigate(['/dashboard']);
  return false;
};

export const departmentGuard: CanActivateFn = (route, state) => {
  const authService = inject(AuthService);
  const router = inject(Router);
  const notification = inject(NotificationService);

  if (authService.isDepartment()) {
    return true;
  }

  notification.error('This page is only accessible to department users.');
  router.navigate(['/dashboard']);
  return false;
};

export const applicantGuard: CanActivateFn = (route, state) => {
  const authService = inject(AuthService);
  const router = inject(Router);
  const notification = inject(NotificationService);

  if (authService.isApplicant()) {
    return true;
  }

  notification.error('This page is only accessible to applicants.');
  router.navigate(['/dashboard']);
  return false;
};

export const adminGuard: CanActivateFn = (route, state) => {
  const authService = inject(AuthService);
  const router = inject(Router);
  const notification = inject(NotificationService);

  if (authService.isAdmin()) {
    return true;
  }

  notification.error('This page is only accessible to administrators.');
  router.navigate(['/dashboard']);
  return false;
};
