import { verifyAccessToken } from '../../utils/jwt.js';
import { AuthenticationError } from '../../utils/errors.js';
import { getUserById } from '../../services/auth.service.js';

/**
 * Middleware na overenie JWT tokenu
 * Pridá user objekt do req.user ak je token validný
 */
export const authenticate = async (req, res, next) => {
  try {
    // Získaj token z Authorization header alebo cookies
    let token = null;

    // Skús Authorization header (Bearer token)
    const authHeader = req.headers.authorization;
    if (authHeader && authHeader.startsWith('Bearer ')) {
      token = authHeader.substring(7);
    }

    // Ak nie je v header, skús cookies
    if (!token && req.cookies && req.cookies.accessToken) {
      token = req.cookies.accessToken;
    }

    if (!token) {
      throw new AuthenticationError('Token nie je poskytnutý');
    }

    // Overenie tokenu
    const decoded = verifyAccessToken(token);

    // Načítaj aktuálne user data z DB
    const user = await getUserById(decoded.id);

    // Pridaj user do requestu
    req.user = user;
    req.userId = user.id;

    next();
  } catch (error) {
    if (error instanceof AuthenticationError) {
      return res.status(401).json({
        success: false,
        error: {
          message: error.message,
          statusCode: 401,
        },
      });
    }

    return next(error);
  }
};
