const db = require('../db');
const { AppError } = require('../utils/helpers');

async function requireAuth(req, _res, next) {
  try {
    const header = req.headers.authorization || '';
    const match = header.match(/^Bearer\s+(\S+)/);
    if (!match) throw new AppError(401, 'Login required');

    const [rows] = await db.query(
      `SELECT u.id, u.name, u.mobile
       FROM sessions s
       JOIN users u ON u.id = s.user_id
       WHERE s.token = ?`,
      [match[1]],
    );
    if (!rows[0]) throw new AppError(401, 'Invalid session');

    req.user = rows[0];
    next();
  } catch (err) {
    next(err);
  }
}

module.exports = { requireAuth };
