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

const allowedTypes = [
  'order',
  'trade',
  'deposit',
  'withdrawal',
  'transfer',
  'price_alert',
  'security',
  'system',
  'promo',
  'referral',
  'staking',
  'copy_trade',
  'verification',
  'support',
];

const allowedPriorities = ['low', 'medium', 'high', 'urgent'];

router.get(
  '/',
  authenticate,
  [
    query('type').optional().isIn(allowedTypes),
    query('read').optional().isBoolean(),
    query('page').optional().isInt({ min: 1 }).toInt(),
    query('limit').optional().isInt({ min: 1, max: 100 }).toInt(),
  ],
  validate,
  notificationController.getNotifications
);

router.get(
  '/get',
  authenticate,
  [
    query('type').optional().isIn(allowedTypes),
    query('read').optional().isBoolean(),
    query('page').optional().isInt({ min: 1 }).toInt(),
    query('limit').optional().isInt({ min: 1, max: 100 }).toInt(),
  ],
  validate,
  notificationController.getNotifications
);

router.get('/unread/count', authenticate, notificationController.getUnreadCount);

router.post(
  '/create',
  [
    body('userId').optional().isInt({ min: 1 }).toInt(),
    body('id').optional().isInt({ min: 1 }).toInt(),
    body('type').isIn(allowedTypes),
    body('title').trim().isLength({ min: 1, max: 255 }),
    body('message').trim().isLength({ min: 1 }),
    body('icon').optional().isString().isLength({ max: 50 }),
    body('color').optional().isString().isLength({ max: 20 }),
    body('link').optional().isString().isLength({ max: 500 }),
    body('priority').optional().isIn(allowedPriorities),
    body('relatedId').optional().isInt({ min: 1 }).toInt(),
    body('relatedType').optional().isString().isLength({ max: 50 }),
    body('metadata').optional().isObject(),
    body('channels').optional().isObject(),
    body('expiresAt').optional().isISO8601(),
  ],
  validate,
  notificationController.createNotification
);

router.get(
  '/:id',
  authenticate,
  [param('id').isInt({ min: 1 }).toInt()],
  validate,
  notificationController.getNotificationById
);

router.put(
  '/:id/read',
  authenticate,
  [param('id').isInt({ min: 1 }).toInt()],
  validate,
  notificationController.markAsRead
);

router.put('/read-all', authenticate, notificationController.markAllAsRead);

router.delete(
  '/:id',
  authenticate,
  [param('id').isInt({ min: 1 }).toInt()],
  validate,
  notificationController.deleteNotification
);

router.delete('/', authenticate, notificationController.deleteAllNotifications);

module.exports = router;