import { env } from '../config/env.js';
import { verifyAccessToken } from '../services/token.service.js';

export async function authRequired(req, res, next) {
  try {
    let token = req.cookies?.[env.COOKIE_ACCESS_NAME];

    // Если нет cookie — пробуем Authorization: Bearer <token>
    if (!token) {
      const auth = req.headers['authorization'];
      if (auth && auth.startsWith('Bearer ')) {
        token = auth.slice(7);
      }
    }

    if (!token) {
      return res.status(401).json({ error: 'UNAUTHORIZED', message: 'Access token is missing' });
    }

    const payload = await verifyAccessToken(token);

    req.user = {
      id: payload.sub,
      role: payload.role,
      email: payload.email,
      sessionId: payload.sid,
    };

    next();
  } catch (err) {
    return res.status(401).json({ error: 'UNAUTHORIZED', message: 'Invalid access token' });
  }
}
