const express = require('express');
const router = express.Router();
const spotController = require('../controllers/spotController');
const { authenticate } = require('../middleware/auth');
const { tradingLimiter } = require('../middleware/rateLimiter');
const { validate, body, query, param } = require('../middleware/validation');

router.get('/', authenticate, spotController.getSpotData)

router.post(
    "/orders",
    authenticate,
    tradingLimiter,
    [
        body("symbol").trim().notEmpty().withMessage("Symbol is required"),
        body("side").isIn(["buy", "sell"]).withMessage("Invalid side"),
        body("orderType")
            .isIn(["market", "limit", "stop-limit"])
            .withMessage("Invalid order type"),
        body("amount").isFloat({ min: 0.00000001 }).withMessage("Invalid amount"),
        body("price")
            .optional({ nullable: true })
            .isFloat({ min: 0.00000001 })
            .withMessage("Invalid price"),
        body("stopPrice")
            .optional({ nullable: true })
            .isFloat({ min: 0.00000001 })
            .withMessage("Invalid stop price"),
        body("clientOrderId")
            .optional()
            .isString()
            .isLength({ max: 64 }),
    ],
    validate,
    spotController.tradeSpot
);

router.delete(
    "/orders/:id",
    authenticate,
    [param("id").isInt({ min: 1 }).withMessage("Invalid order id")],
    validate,
    spotController.cancelSpotOrder
);

router.get(
    "/orders/open",
    authenticate,
    [
        query("symbol").optional().trim().notEmpty(),
        query("side").optional().isIn(["buy", "sell"]),
        query("limit").optional().isInt({ min: 1, max: 200 }),
        query("page").optional().isInt({ min: 1 }),
    ],
    validate,
    spotController.getOpenSpotOrders
);

router.get(
    "/orders/history",
    authenticate,
    [
        query("symbol").optional().trim().notEmpty(),
        query("side").optional().isIn(["buy", "sell"]),
        query("status")
            .optional()
            .isIn(["new", "partially_filled", "filled", "canceled", "rejected"]),
        query("limit").optional().isInt({ min: 1, max: 200 }),
        query("page").optional().isInt({ min: 1 }),
    ],
    validate,
    spotController.getSpotOrderHistory
);

router.get(
    "/trades",
    authenticate,
    [
        query("symbol").optional().trim().notEmpty(),
        query("role").optional().isIn(["maker", "taker", "any"]),
        query("limit").optional().isInt({ min: 1, max: 200 }),
        query("page").optional().isInt({ min: 1 }),
    ],
    validate,
    spotController.getSpotTrades
);

router.get(
    "/orderbook",
    [
        query("symbol").trim().notEmpty().withMessage("Symbol is required"),
        query("depth").optional().isInt({ min: 1, max: 500 }),
    ],
    validate,
    spotController.getSpotOrderBook
);

module.exports = router;

