const db = require('../config/database');
const bcrypt = require('bcryptjs');

const authenticateApiKey = async (req, res, next) => {
  try {
    const apiKey = req.headers['x-api-key'];
    
    if (!apiKey) {
      return res.status(401).json({
        error: 'API key requerida',
        code: '99'
      });
    }

    const [keys] = await db.execute(
      'SELECT * FROM api_keys WHERE api_key = ? AND is_active = true',
      [apiKey]
    );

    if (keys.length === 0) {
      return res.status(403).json({
        error: 'API key inválida',
        code: '99'
      });
    }

    req.apiKey = keys[0];
    next();
  } catch (error) {
    console.error('Error en autenticación:', error);
    res.status(500).json({ error: 'Error interno del servidor' });
  }
};

module.exports = { authenticateApiKey };