import { permissionRegistry, ensureEntityPermissionsLoaded } from "./init.js";
import { queryOneWithRLS } from "../db.js";
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) {
    if (process.env.NODE_ENV === "development") {
      console.log(`[checkPermission] User ${userId} is not a member of team ${teamId}`);
    }
    return false;
  }
  const hasPermission = permissionRegistry.hasPermission(teamRole, permission);
  if (process.env.NODE_ENV === "development") {
    console.log(`[checkPermission] Role: ${teamRole}, Perm: ${permission}, Has: ${hasPermission}`);
  }
  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
};
