const express = require('express');
const router = express.Router();
const candleController = require('../controllers/candleController');
const { validate, validateQuery, validateParams } = require('../middleware/validation');
const Joi = require('joi');

// GET /api/candles - Get candles with filtering
router.get('/', validateQuery(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)
})), candleController.getCandles);

// GET /api/candles/ohlc - Get OHLC data
router.get('/ohlc', validateQuery(Joi.object({
  symbolId: Joi.number().integer().positive().required(),
  period: Joi.string().valid('1h').default('1h'),
  limit: Joi.number().integer().min(1).max(1000).default(100)
})), candleController.getOHLC);

// GET /api/candles/:symbolId/latest - Get latest candle for a symbol
router.get('/:symbolId/latest', validateParams(Joi.object({
  symbolId: Joi.number().integer().positive().required()
})), candleController.getLatestCandle);

// POST /api/candles - Create new candle
router.post('/', validate(Joi.object({
  symbolId: Joi.number().integer().positive().required(),
  openTime: Joi.date().iso().required(),
  closeTime: Joi.date().iso().required(),
  open: Joi.number().precision(8).positive().required(),
  high: Joi.number().precision(8).positive().required(),
  low: Joi.number().precision(8).positive().required(),
  close: Joi.number().precision(8).positive().required(),
  volume: Joi.number().precision(8).positive(),
  tradesCount: Joi.number().integer().min(0),
  quoteVolume: Joi.number().precision(8).positive()
})), candleController.createCandle);

// POST /api/candles/bulk - Bulk create candles
router.post('/bulk', validate(Joi.object({
  candles: Joi.array().items(Joi.object({
    symbolId: Joi.number().integer().positive().required(),
    openTime: Joi.date().iso().required(),
    closeTime: Joi.date().iso().required(),
    open: Joi.number().precision(8).positive().required(),
    high: Joi.number().precision(8).positive().required(),
    low: Joi.number().precision(8).positive().required(),
    close: Joi.number().precision(8).positive().required(),
    volume: Joi.number().precision(8).positive(),
    tradesCount: Joi.number().integer().min(0),
    quoteVolume: Joi.number().precision(8).positive()
  })).min(1).required()
})), candleController.bulkCreateCandles);

// DELETE /api/candles/cleanup/:symbolId - Clean up old candles, keep latest N
router.delete('/cleanup/:symbolId', validateParams(Joi.object({
  symbolId: Joi.number().integer().positive().required()
})), validateQuery(Joi.object({
  keep: Joi.number().integer().min(1).default(1000)
})), candleController.cleanupCandles);

module.exports = router;
