const Joi = require('joi');

const querySchema = Joi.object({
  query: Joi.string().min(3).max(500).required().messages({
    'string.min': 'Query must be at least 3 characters long',
    'string.max': 'Query must not exceed 500 characters',
    'any.required': 'Query is required'
  }),
  sessionId: Joi.string().optional(),
  context: Joi.object().optional()
});

const validateQuery = (req, res, next) => {
  const { error, value } = querySchema.validate(req.body);
  
  if (error) {
    return res.status(400).json({
      success: false,
      message: 'Validation error',
      errors: error.details.map(detail => detail.message)
    });
  }
  
  req.validatedData = value;
  next();
};

const errorHandler = (err, req, res, next) => {
  console.error('Error:', err);

  // Database errors
  if (err.code === 'ER_ACCESS_DENIED_ERROR') {
    return res.status(500).json({
      success: false,
      message: 'Database connection error'
    });
  }

  if (err.code === 'ER_NO_SUCH_TABLE') {
    return res.status(500).json({
      success: false,
      message: 'Database table not found'
    });
  }

  // SQL errors
  if (err.code && err.code.startsWith('ER_')) {
    return res.status(500).json({
      success: false,
      message: 'Database query error',
      details: process.env.NODE_ENV === 'development' ? err.message : undefined
    });
  }

  // Default error
  res.status(500).json({
    success: false,
    message: 'Internal server error',
    details: process.env.NODE_ENV === 'development' ? err.message : undefined
  });
};

module.exports = {
  validateQuery,
  errorHandler
};

