import { ForbiddenException } from '@nestjs/common';
import { User } from '../users/entities/user.entity';

export const ADMIN_ROLE = 'super_admin';
export const AGENT_ROLE = 'agent';
export const NORMAL_USER_ROLE = 'user';

export function getRoleCodes(user: User) {
  return (user.roles || []).map((role) => role.code);
}

export function isAdmin(user: User) {
  return getRoleCodes(user).includes(ADMIN_ROLE);
}

export function isAgent(user: User) {
  return getRoleCodes(user).includes(AGENT_ROLE);
}

export function assertCanManageUsers(user: User) {
  if (!isAdmin(user) && !isAgent(user)) {
    throw new ForbiddenException('No permission to manage users');
  }
}

export function assertAdmin(user: User) {
  if (!isAdmin(user)) {
    throw new ForbiddenException('Only administrators can perform this action');
  }
}

export function assertCanManageTarget(actor: User, target: User) {
  if (isAdmin(actor)) {
    return;
  }

  if (
    isAgent(actor) &&
    (target.parentId === actor.id || target.parentPath?.includes(`/${actor.id}/`))
  ) {
    return;
  }

  throw new ForbiddenException('No permission to manage this user');
}
