const express = require('express');
const { body, query, param } = require('express-validator');
const appointmentController = require('../controllers/appointmentController');
const { authenticateUser } = require('../middleware/auth');

const router = express.Router();

/**
 * Appointment Routes
 * All routes require user authentication
 */

/**
 * @route   POST /api/v1/appointments
 * @desc    Create a new appointment
 * @access  Private (User)
 */
router.post(
  '/',
  authenticateUser,
  [
    // 服务来源（serviceId 或 hotServiceId 至少有一个）
    body('serviceId').optional({ nullable: true }).isUUID().withMessage('Service ID must be a valid UUID'),
    body('hotServiceId').optional({ nullable: true }).isInt().withMessage('Hot Service ID must be an integer'),
    body('serviceType').optional({ nullable: true }).isString().withMessage('Service type must be a string'),
    body('realName').trim().notEmpty().withMessage('Real name is required'),
    // 旧的联系方式字段（可选）
    body('contactMethod')
      .optional({ nullable: true })
      .isIn(['phone', 'whatsapp', 'wechat'])
      .withMessage('Contact method must be one of: phone, whatsapp, wechat'),
    body('contactValue').optional({ nullable: true }).isString().withMessage('Contact value must be a string'),
    // 新的多联系方式字段
    body('wechatId').optional({ nullable: true }).isString().withMessage('WeChat ID must be a string'),
    body('phone').optional({ nullable: true }).isString().withMessage('Phone must be a string'),
    body('phoneCountryCode').optional({ nullable: true }).isString().withMessage('Phone country code must be a string'),
    body('whatsapp').optional({ nullable: true }).isString().withMessage('WhatsApp must be a string'),
    // 通用预约字段
    body('appointmentDate').optional({ nullable: true }).isDate().withMessage('Appointment date must be a valid date'),
    body('appointmentTime').optional({ nullable: true }).matches(/^([0-1]?[0-9]|2[0-3]):[0-5][0-9](:[0-5][0-9])?$/).withMessage('Appointment time must be in HH:MM or HH:MM:SS format'),
    body('notes').optional({ nullable: true }).isString().withMessage('Notes must be a string'),
    body('amount').optional({ nullable: true }).isDecimal().withMessage('Amount must be a decimal number'),
    // 机票预约专用字段
    body('tripType').optional({ nullable: true }).isIn(['single', 'round']).withMessage('Trip type must be single or round'),
    body('departureDate').optional({ nullable: true }).isDate().withMessage('Departure date must be a valid date'),
    body('returnDate').optional({ nullable: true }).isDate().withMessage('Return date must be a valid date'),
    body('departureCity').optional({ nullable: true }).isString().withMessage('Departure city must be a string'),
    body('arrivalCity').optional({ nullable: true }).isString().withMessage('Arrival city must be a string'),
    body('adultCount').optional({ nullable: true }).isInt({ min: 0 }).withMessage('Adult count must be a non-negative integer'),
    body('childCount').optional({ nullable: true }).isInt({ min: 0 }).withMessage('Child count must be a non-negative integer'),
    body('infantCount').optional({ nullable: true }).isInt({ min: 0 }).withMessage('Infant count must be a non-negative integer'),
    body('cabinType').optional({ nullable: true }).isIn(['economy', 'premium_economy', 'business']).withMessage('Cabin type must be economy, premium_economy or business'),
    body('luggageCount').optional({ nullable: true }).isInt({ min: 0 }).withMessage('Luggage count must be a non-negative integer'),
  ],
  appointmentController.createAppointment
);

/**
 * @route   GET /api/v1/appointments/stats
 * @desc    Get user's appointment statistics (counts by status)
 * @access  Private (User)
 */
router.get(
  '/stats',
  authenticateUser,
  appointmentController.getAppointmentStats
);

/**
 * @route   GET /api/v1/appointments
 * @desc    Get user's appointments with filtering and pagination
 * @access  Private (User)
 */
router.get(
  '/',
  authenticateUser,
  [
    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('status')
      .optional()
      .isIn(['pending', 'confirmed', 'in-progress', 'completed', 'cancelled'])
      .withMessage('Status must be one of: pending, confirmed, in-progress, completed, cancelled'),
  ],
  appointmentController.getAppointments
);

/**
 * @route   GET /api/v1/appointments/:id
 * @desc    Get appointment details by ID
 * @access  Private (User)
 */
router.get(
  '/:id',
  authenticateUser,
  [param('id').isUUID().withMessage('Appointment ID must be a valid UUID')],
  appointmentController.getAppointmentById
);

/**
 * @route   PUT /api/v1/appointments/:id
 * @desc    Update appointment
 * @access  Private (User)
 */
router.put(
  '/:id',
  authenticateUser,
  [
    param('id').isUUID().withMessage('Appointment ID must be a valid UUID'),
    body('realName').optional().trim().notEmpty().withMessage('Real name cannot be empty'),
    body('contactMethod')
      .optional()
      .isIn(['phone', 'whatsapp', 'wechat'])
      .withMessage('Contact method must be one of: phone, whatsapp, wechat'),
    body('contactValue').optional().trim().notEmpty().withMessage('Contact value cannot be empty'),
    body('appointmentDate').optional().isDate().withMessage('Appointment date must be a valid date'),
    body('appointmentTime').optional().matches(/^([0-1]?[0-9]|2[0-3]):[0-5][0-9](:[0-5][0-9])?$/).withMessage('Appointment time must be in HH:MM or HH:MM:SS format'),
    body('notes').optional().isString().withMessage('Notes must be a string'),
    body('status')
      .optional()
      .isIn(['pending', 'confirmed', 'in-progress', 'completed', 'cancelled'])
      .withMessage('Status must be one of: pending, confirmed, in-progress, completed, cancelled'),
  ],
  appointmentController.updateAppointment
);

/**
 * @route   DELETE /api/v1/appointments/:id
 * @desc    Cancel appointment
 * @access  Private (User)
 */
router.delete(
  '/:id',
  authenticateUser,
  [param('id').isUUID().withMessage('Appointment ID must be a valid UUID')],
  appointmentController.cancelAppointment
);

module.exports = router;
