const db = require('../plugin/DataBase/db');

class AccessControl {
    async checkSession(uuid, session) {
        const sql = 'SELECT uuid, session FROM users WHERE uuid = ? AND session = ?';
        const rows = await db.query(sql, [uuid, session]);
        return rows.length > 0;
    }

    async getPermission(uuid) {
        const groups = [];
        const sql = 'SELECT admin, manage FROM users WHERE uuid = ?';
        const rows = await db.query(sql, [uuid]);

        if (rows.length === 0) return groups;

        if (rows[0].admin === 1) groups.push('admin');
        if (rows[0].manage === 1) groups.push('manage');

        return groups;
    }

    async checkUser(maintainers, isAdmin = false) {
        if (Array.isArray(maintainers) && maintainers.length > 0) {
            let uuids = [];

            let queries = maintainers.map(async (maintainer) => {
                let sql = 'SELECT uuid FROM `users` WHERE username = ?';
                if(isAdmin) 
                    sql = 'SELECT uuid FROM `users` WHERE username = ? AND manage = 1';
                const rows = await db.query(sql, [maintainer]);

                if (!rows || rows.length === 0) {
                    throw new Error(`未找到已认证用户: ${maintainer}`);
                }

                const uuid = rows[0].uuid;

                return uuid;
            });

            try {
                uuids = await Promise.all(queries);
            } catch (error) {
                throw error;
            }

            return uuids;
        }
        return [];
    }
}

module.exports = new AccessControl();
