"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isValidRoleType = isValidRoleType;
exports.addUserRole = addUserRole;
exports.removeUserRole = removeUserRole;
exports.getUserRoles = getUserRoles;
exports.hasRole = hasRole;
exports.hasRoleType = hasRoleType;
const db_1 = require("../../lib/db");
const sql_1 = require("./sql");
const types_1 = require("./types");
// ─── Role management ──────────────────────────────────────────────────────────
function isValidRoleType(type) {
    return types_1.VALID_ROLE_TYPES.includes(type);
}
async function addUserRole(userId, role, type) {
    const pool = (0, db_1.getPool)();
    // Ensure the role exists in lt_roles (FK constraint)
    await pool.query(sql_1.ENSURE_ROLE_EXISTS, [role]);
    const { rows } = await pool.query(sql_1.UPSERT_USER_ROLE, [userId, role, type]);
    return rows[0];
}
async function removeUserRole(userId, role) {
    const pool = (0, db_1.getPool)();
    const { rowCount } = await pool.query(sql_1.DELETE_USER_ROLE, [userId, role]);
    return (rowCount ?? 0) > 0;
}
async function getUserRoles(userId) {
    const pool = (0, db_1.getPool)();
    const { rows } = await pool.query(sql_1.GET_ROLES_BY_USER_ID, [userId]);
    return rows;
}
async function hasRole(userId, role) {
    const pool = (0, db_1.getPool)();
    const { rows } = await pool.query(sql_1.HAS_ROLE, [userId, role]);
    return rows.length > 0;
}
async function hasRoleType(userId, type) {
    const pool = (0, db_1.getPool)();
    const { rows } = await pool.query(sql_1.HAS_ROLE_TYPE, [userId, type]);
    return rows.length > 0;
}
