const { verifyToken } = require("./security.cjs");

function publicUser(user) {
    if (!user) return null;
    const { password, current_token, ...safeUser } = user;
    return safeUser;
}

function findUserByToken(db, token) {
    const payload = verifyToken(token);
    if (!payload?.userId) return null;
    return db.users.find(user => Number(user.id) === Number(payload.userId)) || null;
}

function getBearerToken(req) {
    const header = req.headers.authorization || "";
    const match = String(header).match(/^Bearer\s+(.+)$/i);
    return match ? match[1] : "";
}

function requireAdmin(db, req) {
    const user = findUserByToken(db, getBearerToken(req));
    if (!user || user.status !== "active") return null;
    if (user.role !== "admin" && Number(user.is_super_admin || 0) !== 1) return null;
    return user;
}

module.exports = {
    publicUser,
    findUserByToken,
    getBearerToken,
    requireAdmin,
};
