const query = require('../storage/database').query;
const { parseSessionToken } = require('../tools/security');

async function getSessions(username) {
    const result = await query('SELECT s.id, s.session_code, s.browser, s.os, s.device_type, s.created_at, s.last_active, s.is_revoked FROM sessions s JOIN users u ON s.user_id = u.id WHERE u.username = $1 AND s.is_revoked = FALSE ORDER BY s.last_active DESC', [username]);

    return result.rows.map(s => ({
        id: s.id,
        code: s.session_code,
        browser: s.browser,
        os: s.os,
        deviceType: s.device_type,
        createdAt: s.created_at?.toLocaleDateString('it-IT', {
            month: 'short', day: 'numeric', year: 'numeric', hour: '2-digit', minute: '2-digit'
        }),
        lastActive: s.last_active?.toLocaleDateString('it-IT', {
            month: 'short', day: 'numeric', year: 'numeric', hour: '2-digit', minute: '2-digit'
        }),
        isRevoked: s.is_revoked,
        isCurrent: false
    }));
};

async function getCurrentSessionID(token) {
    const parsed = parseSessionToken(token);
    if (!parsed) {
        throw new Error('Invalid token');
    }

    const result = await query('SELECT id FROM sessions WHERE session_code = $1', [parsed]);
    return result.rows[0]?.id || null;
}

async function revoke(id, username) {
    const result = await query('UPDATE sessions s SET is_revoked = TRUE FROM users u WHERE s.id = $1 AND s.user_id = u.id AND u.username = $2', [id, username]);
    return result.rowCount > 0;
}

async function revokeOthers(username, current) {
    const result = await query('UPDATE sessions s SET is_revoked = TRUE FROM users u WHERE s.user_id = u.id AND u.username = $1 AND s.id != $2 AND s.is_revoked = FALSE', [username, current]);
    return result.rowCount;
}

async function getCount(username) {
    const result = await query('SELECT COUNT(*) as count FROM sessions s JOIN users u ON s.user_id = u.id WHERE u.username = $1 AND s.is_revoked = FALSE', [username]);
    return parseInt(result.rows[0].count, 10);
}

module.exports = {
    getSessions,
    getCurrentSessionID,
    revoke,
    revokeOthers,
    getCount
};

