export async function usersRoutes(app, opts) {
    const { db } = opts;
    // GET /api/users (admin only)
    app.get('/api/users', { preHandler: [app.requireAuth, app.requireRole('admin')] }, async () => {
        const users = db
            .prepare('SELECT id, username, email, role, created_at, last_login FROM users')
            .all();
        return { users };
    });
    // PATCH /api/users/:id (admin only)
    app.patch('/api/users/:id', { preHandler: [app.requireAuth, app.requireRole('admin')] }, async (request, reply) => {
        const { id } = request.params;
        const { role } = request.body;
        const validRoles = ['admin', 'operator', 'viewer'];
        if (!role || !validRoles.includes(role)) {
            return reply.code(400).send({ error: 'Invalid role. Must be admin, operator, or viewer.' });
        }
        const user = db.prepare('SELECT id FROM users WHERE id = ?').get(id);
        if (!user) {
            return reply.code(404).send({ error: 'User not found' });
        }
        db.prepare('UPDATE users SET role = ? WHERE id = ?').run(role, id);
        const updated = db
            .prepare('SELECT id, username, email, role, created_at, last_login FROM users WHERE id = ?')
            .get(id);
        return { user: updated };
    });
    // DELETE /api/users/:id (admin only)
    app.delete('/api/users/:id', { preHandler: [app.requireAuth, app.requireRole('admin')] }, async (request, reply) => {
        const { id } = request.params;
        if (id === request.user.userId) {
            return reply.code(400).send({ error: 'Cannot delete yourself' });
        }
        const user = db.prepare('SELECT id FROM users WHERE id = ?').get(id);
        if (!user) {
            return reply.code(404).send({ error: 'User not found' });
        }
        db.prepare('DELETE FROM sessions WHERE user_id = ?').run(id);
        db.prepare('DELETE FROM users WHERE id = ?').run(id);
        // Audit log
        db.prepare('INSERT INTO audit_log (user_id, action, details, created_at) VALUES (?, ?, ?, ?)').run(request.user.userId, 'delete_user', JSON.stringify({ deletedUserId: id }), new Date().toISOString());
        return { ok: true };
    });
}
//# sourceMappingURL=users-routes.js.map