const Joi = require('joi');

// Symbol validation schemas
const symbolSchema = Joi.object({
  symbol: Joi.string().max(50).required(),
  baseAsset: Joi.string().max(50),
  quoteAsset: Joi.string().max(50),
  exchange: Joi.string().max(50),
  instrumentType: Joi.string().valid('crypto', 'stock', 'forex', 'commodity').required(),
  isActive: Joi.boolean().default(true)
});

const symbolIdSchema = Joi.object({
  id: Joi.number().integer().positive().required()
});

// Candle validation schemas
const candleSchema = Joi.object({
  symbolId: Joi.number().integer().positive().required(),
  openTime: Joi.date().iso().required(),
  closeTime: Joi.date().iso().required(),
  open: Joi.number().precision(15).required(),
  high: Joi.number().precision(15).required(),
  low: Joi.number().precision(15).required(),
  close: Joi.number().precision(15).required(),
  volume: Joi.number().precision(15).required()
});

const candleQuerySchema = Joi.object({
  symbolId: Joi.number().integer().positive().required(),
  startTime: Joi.date().iso(),
  endTime: Joi.date().iso().when('startTime', {
    is: Joi.exist(),
    then: Joi.date().iso().greater(Joi.ref('startTime'))
  }),
  limit: Joi.number().integer().min(1).max(1000).default(100),
  offset: Joi.number().integer().min(0).default(0)
});

// Live price validation schemas
const livePriceSchema = Joi.object({
  symbolId: Joi.number().integer().positive().required(),
  price: Joi.number().precision(15).positive().required(),
  bid: Joi.number().precision(15).positive(),
  ask: Joi.number().precision(15).positive(),
  bidSize: Joi.number().precision(15).positive(),
  askSize: Joi.number().precision(15).positive()
});

// Middleware functions
const validate = (schema) => {
  return (req, res, next) => {
    const { error, value } = schema.validate(req.body, { abortEarly: false });

    if (error) {
      error.isJoi = true;
      return next(error);
    }

    req.body = value;
    next();
  };
};

const validateQuery = (schema) => {
  return (req, res, next) => {
    const { error, value } = schema.validate(req.query, { abortEarly: false });

    if (error) {
      error.isJoi = true;
      return next(error);
    }

    req.query = value;
    next();
  };
};

const validateParams = (schema) => {
  return (req, res, next) => {
    const { error, value } = schema.validate(req.params, { abortEarly: false });

    if (error) {
      error.isJoi = true;
      return next(error);
    }

    req.params = value;
    next();
  };
};

module.exports = {
  symbolSchema,
  symbolIdSchema,
  candleQuerySchema,
  livePriceSchema,
  validate,
  validateQuery,
  validateParams
};
