// apps/api/src/middleware/auth.middleware.js

const jwt = require('jsonwebtoken');
const { DatabaseClient } = require('../../../../packages/db/client');

const db = new DatabaseClient();

async function authMiddleware(req, res, next) {
    try {
        const token = req.headers.authorization?.replace('Bearer ', '');
        
        if (!token) {
            return res.status(401).json({ error: 'No token provided' });
        }
        
        const decoded = jwt.verify(token, process.env.JWT_SECRET);
        
        const user = await db.get(
            'SELECT id, email, role, is_active FROM users WHERE id = ?',
            [decoded.id]
        );
        
        if (!user || !user.is_active) {
            return res.status(401).json({ error: 'User not found or inactive' });
        }
        
        req.user = user;
        next();
    } catch (error) {
        if (error.name === 'JsonWebTokenError') {
            return res.status(401).json({ error: 'Invalid token' });
        }
        if (error.name === 'TokenExpiredError') {
            return res.status(401).json({ error: 'Token expired' });
        }
        console.error('Auth middleware error:', error);
        res.status(500).json({ error: 'Authentication failed' });
    }
}

module.exports = authMiddleware;