'use strict';

const express = require('express');
const router = express.Router();
const { body, param, query } = require('express-validator');
const supplierController = require('../controllers/supplierController');

// Validation middleware
const validateSupplierCreate = [
  body('name')
    .trim()
    .notEmpty()
    .withMessage('Supplier name is required')
    .isLength({ min: 2, max: 255 })
    .withMessage('Supplier name must be between 2 and 255 characters'),
  body('contactPerson')
    .optional()
    .trim()
    .isLength({ max: 255 })
    .withMessage('Contact person name must not exceed 255 characters'),
  body('email')
    .optional()
    .trim()
    .isEmail()
    .withMessage('Invalid email format')
    .normalizeEmail(),
  body('phone')
    .optional()
    .trim()
    .matches(/^[+]?[(]?[0-9]{1,4}[)]?[-\s./0-9]*$/)
    .withMessage('Invalid phone number format'),
  body('address')
    .optional()
    .trim()
    .isLength({ max: 500 })
    .withMessage('Address must not exceed 500 characters'),
  body('city')
    .optional()
    .trim()
    .isLength({ max: 100 })
    .withMessage('City must not exceed 100 characters'),
  body('country')
    .optional()
    .trim()
    .isLength({ max: 100 })
    .withMessage('Country must not exceed 100 characters'),
  body('taxId')
    .optional()
    .trim()
    .isLength({ max: 50 })
    .withMessage('Tax ID must not exceed 50 characters'),
  body('paymentTerms')
    .optional()
    .trim()
    .isLength({ max: 255 })
    .withMessage('Payment terms must not exceed 255 characters'),
  body('isActive')
    .optional()
    .isBoolean()
    .withMessage('isActive must be a boolean value')
];

const validateSupplierUpdate = [
  param('id')
    .isInt({ min: 1 })
    .withMessage('Invalid supplier ID'),
  body('name')
    .optional()
    .trim()
    .notEmpty()
    .withMessage('Supplier name cannot be empty')
    .isLength({ min: 2, max: 255 })
    .withMessage('Supplier name must be between 2 and 255 characters'),
  body('contactPerson')
    .optional()
    .trim()
    .isLength({ max: 255 })
    .withMessage('Contact person name must not exceed 255 characters'),
  body('email')
    .optional()
    .trim()
    .isEmail()
    .withMessage('Invalid email format')
    .normalizeEmail(),
  body('phone')
    .optional()
    .trim()
    .matches(/^[+]?[(]?[0-9]{1,4}[)]?[-\s./0-9]*$/)
    .withMessage('Invalid phone number format'),
  body('address')
    .optional()
    .trim()
    .isLength({ max: 500 })
    .withMessage('Address must not exceed 500 characters'),
  body('city')
    .optional()
    .trim()
    .isLength({ max: 100 })
    .withMessage('City must not exceed 100 characters'),
  body('country')
    .optional()
    .trim()
    .isLength({ max: 100 })
    .withMessage('Country must not exceed 100 characters'),
  body('taxId')
    .optional()
    .trim()
    .isLength({ max: 50 })
    .withMessage('Tax ID must not exceed 50 characters'),
  body('paymentTerms')
    .optional()
    .trim()
    .isLength({ max: 255 })
    .withMessage('Payment terms must not exceed 255 characters'),
  body('isActive')
    .optional()
    .isBoolean()
    .withMessage('isActive must be a boolean value')
];

const validateSupplierId = [
  param('id')
    .isInt({ min: 1 })
    .withMessage('Invalid supplier ID')
];

const validateGetAllSuppliers = [
  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('search')
    .optional()
    .trim()
    .isLength({ max: 255 })
    .withMessage('Search query too long'),
  query('isActive')
    .optional()
    .isIn(['true', 'false'])
    .withMessage('isActive must be true or false'),
  query('sortBy')
    .optional()
    .isIn(['id', 'name', 'contactPerson', 'email', 'city', 'country', 'createdAt', 'updatedAt'])
    .withMessage('Invalid sort field'),
  query('sortOrder')
    .optional()
    .isIn(['ASC', 'DESC', 'asc', 'desc'])
    .withMessage('Sort order must be ASC or DESC')
];

const validateBulkOperation = [
  body('operation')
    .notEmpty()
    .withMessage('Operation is required')
    .isIn(['activate', 'deactivate', 'delete'])
    .withMessage('Operation must be activate, deactivate, or delete'),
  body('supplierIds')
    .isArray({ min: 1 })
    .withMessage('supplierIds must be a non-empty array'),
  body('supplierIds.*')
    .isInt({ min: 1 })
    .withMessage('Each supplier ID must be a valid integer')
];

const validateExport = [
  query('format')
    .optional()
    .isIn(['json', 'csv'])
    .withMessage('Format must be json or csv'),
  query('isActive')
    .optional()
    .isIn(['true', 'false'])
    .withMessage('isActive must be true or false')
];

// Routes

// Get all suppliers with pagination and filtering
router.get(
  '/',
  validateGetAllSuppliers,
  supplierController.getAllSuppliers
);

// Export suppliers
router.get(
  '/export',
  validateExport,
  supplierController.exportSuppliers
);

// Bulk operations
router.post(
  '/bulk',
  validateBulkOperation,
  supplierController.bulkOperation
);

// Get supplier statistics
router.get(
  '/:id/statistics',
  validateSupplierId,
  supplierController.getSupplierStatistics
);

// Activate supplier
router.patch(
  '/:id/activate',
  validateSupplierId,
  supplierController.activateSupplier
);

// Get single supplier by ID
router.get(
  '/:id',
  validateSupplierId,
  supplierController.getSupplierById
);

// Create new supplier
router.post(
  '/',
  validateSupplierCreate,
  supplierController.createSupplier
);

// Update supplier
router.put(
  '/:id',
  validateSupplierUpdate,
  supplierController.updateSupplier
);

// Delete/deactivate supplier
router.delete(
  '/:id',
  validateSupplierId,
  supplierController.deleteSupplier
);

module.exports = router;