import { query } from '@zen/core/database';
export { PERMISSIONS, PERMISSION_DEFINITIONS, getPermissionGroups } from './constants.js';
export {
  registerPermission,
  registerPermissions,
  getRegisteredPermissions,
  getRegisteredPermissionKeys,
} from './permissions-registry.js';

export async function hasPermission(userId, permissionKey) {
  const result = await query(
    `SELECT 1
     FROM zen_auth_user_roles ur
     JOIN zen_auth_role_permissions rp ON rp.role_id = ur.role_id
     WHERE ur.user_id = $1
       AND rp.permission_key = $2
     LIMIT 1`,
    [userId, permissionKey]
  );
  return result.rows.length > 0;
}

export async function getUserPermissions(userId) {
  const result = await query(
    `SELECT DISTINCT rp.permission_key
     FROM zen_auth_user_roles ur
     JOIN zen_auth_role_permissions rp ON rp.role_id = ur.role_id
     WHERE ur.user_id = $1`,
    [userId]
  );
  return result.rows.map(r => r.permission_key);
}
