export const PERMISSIONS = {
    USERS_MANAGE: 'users.manage',
    ROLES_MANAGE: 'roles.manage',
    SECURITY_AUDIT_VIEW: 'security.audit.view',
    SETTINGS_MANAGE: 'settings.manage',
    INVOICES_VIEW_ALL: 'invoices.view_all',
    INVOICES_MANAGE: 'invoices.manage',
    INVOICES_ARCHIVE: 'invoices.archive',
    DELIVERIES_APPROVE: 'deliveries.approve',
    DELIVERIES_WAREHOUSE_VIEW: 'deliveries.warehouse_view',
    DELIVERIES_WAREHOUSE_ACT: 'deliveries.warehouse_act',
    DISCREPANCIES_RESOLVE: 'discrepancies.resolve',
    PRODUCTS_MANAGE: 'products.manage',
    REQUESTERS_MANAGE: 'requesters.manage',
    IMPORTS_INVOICES: 'imports.invoices',
    IMPORTS_PRODUCTS: 'imports.products',
    REPORTS_VIEW: 'reports.view',
    AUDIT_VIEW_OPERATIONAL: 'audit.view_operational'
};
export async function getAuthorization(db, userId) {
    const roles = await db.query(`SELECT r.code FROM roles r JOIN user_roles ur ON ur.role_id = r.id WHERE ur.user_id = $1`, [userId]);
    const permissions = await db.query(`SELECT p.code,
      COALESCE(up.allowed, true) AS allowed
     FROM permissions p
     LEFT JOIN user_permissions up ON up.permission_id = p.id AND up.user_id = $1
     WHERE (up.allowed = true OR EXISTS (
       SELECT 1 FROM user_roles ur JOIN role_permissions rp ON rp.role_id = ur.role_id
       WHERE ur.user_id = $1 AND rp.permission_id = p.id
     )) AND COALESCE(up.allowed, true) = true`, [userId]);
    return { userId, roles: roles.rows.map((role) => role.code), permissions: new Set(permissions.rows.map((p) => p.code)) };
}
export async function userHasPermission(db, userId, permission) {
    return (await getAuthorization(db, userId)).permissions.has(permission);
}
//# sourceMappingURL=rbac.js.map