const express = require('express');
const router = express.Router();
const { body, param, query } = require('express-validator');
const { validate } = require('../middleware/validation');
const { authorize } = require('../middleware/auth');
const {
  getAllDeliveryBoys,
  getDeliveryBoyById,
  createDeliveryBoy,
  updateDeliveryBoy,
  deleteDeliveryBoy,
  getNearbyDeliveryBoys,
  updateDeliveryBoyStatus,
  updateDeliveryBoyAvailability
} = require('../controllers/deliveryBoysController');

// Import validation schemas
const { 
  createDeliveryBoySchema, 
  updateDeliveryBoySchema,
  updateStatusSchema,
  updateAvailabilitySchema
} = require('../validations/deliveryBoy.validation');

// Apply authentication and authorization middleware to all routes
router.use(authorize('admin'));

/**
 * @swagger
 * /api/delivery-boys:
 *   get:
 *     summary: Get all delivery boys with pagination
 *     tags: [Delivery Boys]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: query
 *         name: page
 *         schema:
 *           type: integer
 *           default: 1
 *         description: Page number
 *       - in: query
 *         name: limit
 *         schema:
 *           type: integer
 *           default: 10
 *         description: Number of items per page
 *       - in: query
 *         name: search
 *         schema:
 *           type: string
 *         description: Search term for name, email, or phone
 *       - in: query
 *         name: status
 *         schema:
 *           type: string
 *           enum: [pending, approved, rejected, active, inactive, on_leave]
 *         description: Filter by status
 *       - in: query
 *         name: isAvailable
 *         schema:
 *           type: boolean
 *         description: Filter by availability
 *     responses:
 *       200:
 *         description: List of delivery boys with pagination info
 */
router.get('/', validate([
  query('page').optional().isInt({ min: 1 }).toInt(),
  query('limit').optional().isInt({ min: 1, max: 100 }).toInt(),
  query('search').optional().trim(),
  query('status').optional().isIn(['pending', 'approved', 'rejected', 'active', 'inactive', 'on_leave']),
  query('isAvailable').optional().isBoolean().toBoolean()
]), getAllDeliveryBoys);

/**
 * @swagger
 * /api/delivery-boys/nearby:
 *   get:
 *     summary: Get delivery boys near a location
 *     tags: [Delivery Boys]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: query
 *         name: longitude
 *         required: true
 *         schema:
 *           type: number
 *           format: float
 *         description: Longitude of the location
 *       - in: query
 *         name: latitude
 *         required: true
 *         schema:
 *           type: number
 *           format: float
 *         description: Latitude of the location
 *       - in: query
 *         name: maxDistance
 *         schema:
 *           type: integer
 *           default: 5000
 *         description: Maximum distance in meters
 *     responses:
 *       200:
 *         description: List of nearby delivery boys
 */
router.get('/nearby', validate([
  query('longitude').isFloat({ min: -180, max: 180 }).toFloat(),
  query('latitude').isFloat({ min: -90, max: 90 }).toFloat(),
  query('maxDistance').optional().isInt({ min: 1, max: 100000 }).toInt()
]), getNearbyDeliveryBoys);

/**
 * @swagger
 * /api/delivery-boys/{id}:
 *   get:
 *     summary: Get delivery boy by ID
 *     tags: [Delivery Boys]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: string
 *         description: Delivery boy ID
 *     responses:
 *       200:
 *         description: Delivery boy details
 *       404:
 *         description: Delivery boy not found
 */
router.get('/:id', validate([
  param('id').isMongoId().withMessage('Invalid delivery boy ID')
]), getDeliveryBoyById);

/**
 * @swagger
 * /api/delivery-boys:
 *   post:
 *     summary: Create a new delivery boy
 *     tags: [Delivery Boys]
 *     security:
 *       - bearerAuth: []
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             $ref: '#/components/schemas/DeliveryBoy'
 *     responses:
 *       201:
 *         description: Delivery boy created successfully
 *       400:
 *         description: Validation error or user with email/phone already exists
 */
router.post('/', validate(createDeliveryBoySchema), createDeliveryBoy);

/**
 * @swagger
 * /api/delivery-boys/{id}:
 *   put:
 *     summary: Update delivery boy
 *     tags: [Delivery Boys]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: string
 *         description: Delivery boy ID
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             $ref: '#/components/schemas/UpdateDeliveryBoy'
 *     responses:
 *       200:
 *         description: Delivery boy updated successfully
 *       400:
 *         description: Validation error
 *       404:
 *         description: Delivery boy not found
 */
router.put('/:id', validate([
  param('id').isMongoId().withMessage('Invalid delivery boy ID'),
  ...updateDeliveryBoySchema
]), updateDeliveryBoy);

/**
 * @swagger
 * /api/delivery-boys/{id}/status:
 *   patch:
 *     summary: Update delivery boy status
 *     tags: [Delivery Boys]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: string
 *         description: Delivery boy ID
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             required:
 *               - status
 *             properties:
 *               status:
 *                 type: string
 *                 enum: [pending, approved, rejected]
 *     responses:
 *       200:
 *         description: Status updated successfully
 *       400:
 *         description: Invalid status value
 *       404:
 *         description: Delivery boy not found
 */
router.patch('/:id/status', validate([
  param('id').isMongoId().withMessage('Invalid delivery boy ID'),
  ...updateStatusSchema
]), updateDeliveryBoyStatus);

/**
 * @swagger
 * /api/delivery-boys/{id}/availability:
 *   patch:
 *     summary: Update delivery boy availability
 *     tags: [Delivery Boys]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: string
 *         description: Delivery boy ID
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             required:
 *               - isAvailable
 *             properties:
 *               isAvailable:
 *                 type: boolean
 *     responses:
 *       200:
 *         description: Availability updated successfully
 *       400:
 *         description: Invalid input
 *       404:
 *         description: Delivery boy not found
 */
router.patch('/:id/availability', validate([
  param('id').isMongoId().withMessage('Invalid delivery boy ID'),
  ...updateAvailabilitySchema
]), updateDeliveryBoyAvailability);

/**
 * @swagger
 * /api/delivery-boys/{id}:
 *   delete:
 *     summary: Delete a delivery boy
 *     tags: [Delivery Boys]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: string
 *         description: Delivery boy ID
 *     responses:
 *       204:
 *         description: Delivery boy deleted successfully
 *       400:
 *         description: Cannot delete delivery boy with active orders
 *       404:
 *         description: Delivery boy not found
 */
router.delete('/:id', validate([
  param('id').isMongoId().withMessage('Invalid delivery boy ID')
]), deleteDeliveryBoy);

module.exports = router;
