import type { UserRole } from '@/types/api';
import { ADMIN_ROLES } from '@/types/api';

/** Check if the user has any of the specified roles */
export function hasAnyRole(user: { roles?: UserRole[]; role?: UserRole } | null, roles: UserRole[]): boolean {
  if (!user) return false;
  const userRoles = getUserRoles(user);
  return userRoles.some(r => roles.includes(r));
}

/** Check if user has any admin role */
export function isAdmin(user: { roles?: UserRole[]; role?: UserRole } | null): boolean {
  return hasAnyRole(user, ADMIN_ROLES);
}

/** Safely extract roles array from a user (handles old single-role and new multi-role) */
export function getUserRoles(user: { roles?: UserRole[]; role?: UserRole }): UserRole[] {
  if (Array.isArray(user.roles) && user.roles.length > 0) {
    return user.roles;
  }
  if (user.role) return [user.role];
  return ['USER'];
}
