import jwt from 'jsonwebtoken';
import UserToken from '../models/UserToken.js';

export const authenticate = async (req, res, next) => {
  let token = req.headers['authorization']?.split(' ')[1];
  if (!token) {
    token = req.headers['authcode'];
  }
  if (!token) {
    token = req.query?.authcode || req.query?.token || null;
  }
  if (!token) {
    return res.status(401).json({ error: 'Unauthorized: Token fehlt' });
  }
  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    const tokenRecord = await UserToken.findOne({ where: { token } });
    if (!tokenRecord || tokenRecord.expiresAt < new Date()) {
      return res.status(401).json({ error: 'Unauthorized: Invalid credentials' });
    }
    req.user = { id: decoded.userId };
    next();
  } catch (err) {
    return res.status(401).json({ error: 'Unauthorized: Invalid credentials' });
  }
};