import { permissionRegistry, ensureEntityPermissionsLoaded } from "./init";
import { queryOneWithRLS } from "../db";
async function getTeamMemberRole(userId, teamId) {
  const result = await queryOneWithRLS(
    `SELECT role
     FROM "team_members"
     WHERE "userId" = $1
       AND "teamId" = $2
     LIMIT 1`,
    [userId, teamId]
  );
  return (result == null ? void 0 : result.role) || null;
}
async function checkPermission(userId, teamId, permission) {
  ensureEntityPermissionsLoaded();
  const teamRole = await getTeamMemberRole(userId, teamId);
  if (!teamRole) {
    console.log(`[checkPermission] User ${userId} is not a member of team ${teamId}`);
    return false;
  }
  const hasPermission = permissionRegistry.hasPermission(teamRole, permission);
  const permConfig = permissionRegistry.getPermissionConfig(permission);
  const rolePerms = permissionRegistry.getRolePermissions(teamRole);
  console.log(`[checkPermission] ============================================`);
  console.log(`[checkPermission] User role: ${teamRole}, Permission: ${permission}`);
  console.log(`[checkPermission] Has permission: ${hasPermission}`);
  console.log(`[checkPermission] Registry initialized: ${permissionRegistry.isInitialized()}`);
  console.log(`[checkPermission] Permission config exists: ${!!permConfig}`);
  console.log(`[checkPermission] Role ${teamRole} has ${rolePerms.length} permissions`);
  if (permConfig) {
    console.log(`[checkPermission] Permission roles: ${JSON.stringify(permConfig.roles)}`);
  }
  console.log(`[checkPermission] ============================================`);
  return hasPermission;
}
async function checkPermissions(userId, teamId, permissions) {
  for (const permission of permissions) {
    if (!await checkPermission(userId, teamId, permission)) {
      return false;
    }
  }
  return true;
}
async function checkAnyPermission(userId, teamId, permissions) {
  for (const permission of permissions) {
    if (await checkPermission(userId, teamId, permission)) {
      return true;
    }
  }
  return false;
}
async function getUserPermissions(userId, teamId) {
  const teamRole = await getTeamMemberRole(userId, teamId);
  if (!teamRole) {
    return [];
  }
  return permissionRegistry.getRolePermissions(teamRole);
}
function hasPermissionSync(teamRole, permission) {
  return permissionRegistry.hasPermission(teamRole, permission);
}
export {
  checkAnyPermission,
  checkPermission,
  checkPermissions,
  getUserPermissions,
  hasPermissionSync
};
