const express = require('express');
const { body, query, param } = require('express-validator');
const router = express.Router();
const adminServiceController = require('../controllers/adminServiceController');
const { authenticateAdmin } = require('../middleware/auth');
const { logAdminOperation } = require('../middleware/adminLogger');
const { requireRole } = require('../middleware/rbac');

/**
 * Admin Service Management Routes
 * Base path: /api/v1/admin/services
 * All routes require admin authentication
 */

/**
 * @route   GET /api/v1/admin/services
 * @desc    Get service list with pagination and filters
 * @access  Private (Admin)
 */
router.get(
  '/',
  authenticateAdmin,
  requireRole(['super_admin', 'admin', 'operator']),
  [
    query('page').optional().isInt({ min: 1 }).withMessage('Page must be a positive integer'),
    query('limit').optional().isInt({ min: 1, max: 100 }).withMessage('Limit must be between 1 and 100'),
    query('categoryId').optional().isUUID().withMessage('Category ID must be a valid UUID'),
    query('status').optional().isIn(['active', 'inactive']).withMessage('Status must be active or inactive'),
    query('search').optional().isString().withMessage('Search must be a string'),
  ],
  logAdminOperation,
  adminServiceController.getServices
);

/**
 * @route   GET /api/v1/admin/services/:id
 * @desc    Get service details
 * @access  Private (Admin)
 */
router.get(
  '/:id',
  authenticateAdmin,
  requireRole(['super_admin', 'admin', 'operator']),
  [
    param('id').isUUID().withMessage('Service ID must be a valid UUID'),
  ],
  logAdminOperation,
  adminServiceController.getServiceById
);

/**
 * @route   POST /api/v1/admin/services
 * @desc    Create a new service
 * @access  Private (Admin)
 */
router.post(
  '/',
  authenticateAdmin,
  requireRole(['super_admin', 'admin']),
  [
    body('categoryId').isUUID().withMessage('Category ID must be a valid UUID'),
    body('titleZh').notEmpty().withMessage('Chinese title is required'),
    body('titleEn').notEmpty().withMessage('English title is required'),
    body('titleEs').notEmpty().withMessage('Spanish title is required'),
    body('descriptionZh').optional({ nullable: true }).custom((value) => {
      if (value === null || value === undefined) return true;
      if (typeof value !== 'string') throw new Error('Description must be a string');
      return true;
    }),
    body('descriptionEn').optional({ nullable: true }).custom((value) => {
      if (value === null || value === undefined) return true;
      if (typeof value !== 'string') throw new Error('Description must be a string');
      return true;
    }),
    body('descriptionEs').optional({ nullable: true }).custom((value) => {
      if (value === null || value === undefined) return true;
      if (typeof value !== 'string') throw new Error('Description must be a string');
      return true;
    }),
    body('image').optional({ nullable: true }).custom((value) => {
      if (value === null || value === undefined) return true;
      if (typeof value !== 'string') throw new Error('Image must be a string');
      return true;
    }),
    body('price').optional({ nullable: true }).custom((value) => {
      if (value === null || value === undefined || value === '') return true;
      if (isNaN(parseFloat(value))) throw new Error('Price must be a number');
      return true;
    }),
    body('status').optional().isIn(['active', 'inactive']).withMessage('Status must be active or inactive'),
    body('sortOrder').optional().isInt().withMessage('Sort order must be an integer'),
  ],
  logAdminOperation,
  adminServiceController.createService
);

/**
 * @route   PUT /api/v1/admin/services/:id
 * @desc    Update a service
 * @access  Private (Admin)
 */
router.put(
  '/:id',
  authenticateAdmin,
  requireRole(['super_admin', 'admin']),
  [
    param('id').isUUID().withMessage('Service ID must be a valid UUID'),
    body('categoryId').optional().isUUID().withMessage('Category ID must be a valid UUID'),
    body('titleZh').optional().notEmpty().withMessage('Chinese title cannot be empty'),
    body('titleEn').optional().notEmpty().withMessage('English title cannot be empty'),
    body('titleEs').optional().notEmpty().withMessage('Spanish title cannot be empty'),
    body('descriptionZh').optional({ nullable: true }).custom((value) => {
      if (value === null || value === undefined) return true;
      if (typeof value !== 'string') throw new Error('Description must be a string');
      return true;
    }),
    body('descriptionEn').optional({ nullable: true }).custom((value) => {
      if (value === null || value === undefined) return true;
      if (typeof value !== 'string') throw new Error('Description must be a string');
      return true;
    }),
    body('descriptionEs').optional({ nullable: true }).custom((value) => {
      if (value === null || value === undefined) return true;
      if (typeof value !== 'string') throw new Error('Description must be a string');
      return true;
    }),
    body('image').optional({ nullable: true }).custom((value) => {
      if (value === null || value === undefined) return true;
      if (typeof value !== 'string') throw new Error('Image must be a string');
      return true;
    }),
    body('price').optional({ nullable: true }).custom((value) => {
      if (value === null || value === undefined || value === '') return true;
      if (isNaN(parseFloat(value))) throw new Error('Price must be a number');
      return true;
    }),
    body('status').optional().isIn(['active', 'inactive']).withMessage('Status must be active or inactive'),
    body('sortOrder').optional().isInt().withMessage('Sort order must be an integer'),
  ],
  logAdminOperation,
  adminServiceController.updateService
);

/**
 * @route   DELETE /api/v1/admin/services/:id
 * @desc    Delete a service
 * @access  Private (Admin)
 */
router.delete(
  '/:id',
  authenticateAdmin,
  requireRole(['super_admin', 'admin']),
  [
    param('id').isUUID().withMessage('Service ID must be a valid UUID'),
  ],
  logAdminOperation,
  adminServiceController.deleteService
);

module.exports = router;
