const express = require('express')
const router = express.Router()
const DepartmentController = require('../controllers/departmentController')
const { authenticateToken, authorizePermission } = require('../middleware/auth')
const {
  createDepartmentValidation,
  updateDepartmentValidation
} = require('../middleware/departmentValidation')
const { createOptionalImageUploadMiddleware } = require('../middleware/fileUpload')

// All routes require authentication
router.use(authenticateToken)

// GET /api/departments - Get all departments
router.get('/', DepartmentController.getAllDepartments)

// GET /api/departments/statistics - Get department statistics
router.get('/statistics', DepartmentController.getDepartmentStatistics)

// GET /api/departments/hierarchy - Get department hierarchy
router.get('/hierarchy', DepartmentController.getDepartmentHierarchy)

// GET /api/departments/:id/children - Get child departments
router.get('/:id/children', DepartmentController.getChildDepartments)

// GET /api/departments/:id - Get department by ID
router.get('/:id', DepartmentController.getDepartmentById)

// POST /api/departments - Create new department (Permission-based)
// Note: Image upload middleware must come before validation to parse FormData
router.post(
  '/',
  authorizePermission('department.create'),
  createOptionalImageUploadMiddleware('logo', 'department'),
  createDepartmentValidation,
  DepartmentController.createDepartment
)

// PUT /api/departments/:id - Update department (Permission-based)
// Note: Image upload middleware must come before validation to parse FormData
router.put(
  '/:id',
  authorizePermission('department.update'),
  createOptionalImageUploadMiddleware('logo', 'department'),
  updateDepartmentValidation,
  DepartmentController.updateDepartment
)

// DELETE /api/departments/:id - Delete department (Permission-based)
router.delete(
  '/:id',
  authorizePermission('department.delete'),
  DepartmentController.deleteDepartment
)

module.exports = router
