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

class AccessControl {
    parseArray(value) {
        if (Array.isArray(value)) return value
        if (!value) return []
        if (typeof value !== 'string') return []
        try {
            const parsed = JSON.parse(value)
            return Array.isArray(parsed) ? parsed : []
        } catch (_) {
            return []
        }
    }

    normalizeCodes(codes) {
        if (!codes) return []
        const list = Array.isArray(codes) ? codes : [codes]
        return [...new Set(list.map(code => String(code || '').trim()).filter(Boolean))]
    }

    async checkSession(uuid, session) {
        return (await Redis.get(`userSession:${uuid}`)) === session
    }

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

        return this.parseArray(rows[0]?.permission)
    }

    async canAccess(uuid, requiredCodes) {
        const codes = this.normalizeCodes(requiredCodes)
        if (codes.length === 0) return true

        const permission = await this.getPermission(uuid)
        if (permission.includes('admin') || permission.includes('service')) return true

        return codes.some(code => permission.includes(code))
    }

    async checkJwAccount(uuid, username) {
        const sql = 'SELECT password FROM jw_account WHERE create_user = ? AND state = 1 AND username = ?'
        const rows = await db.query(sql, [uuid, username]);
        if (!rows || rows.length !== 1 || !rows[0].password)
            return false
        return rows[0]?.password
    }
}

module.exports = new AccessControl();
