import { Router } from 'express';
import { companiesController } from './companies.controller.js';
import { authenticate } from '../../shared/middleware/auth.middleware.js';
import { requireAccess } from '../../shared/middleware/rbac.middleware.js';

const router = Router();

// All routes require authentication
router.use(authenticate);

// List companies (admin, manager)
router.get('/', requireAccess({ roles: ['admin', 'manager'], permission: 'branches:read' }), (req, res, next) =>
  companiesController.findAll(req, res, next)
);

// Get company hierarchy tree (must be before /:id to avoid conflict)
router.get('/hierarchy/tree', requireAccess({ roles: ['admin', 'manager'], permission: 'branches:read' }), (req, res, next) =>
  companiesController.getHierarchy(req, res, next)
);

// Get company by ID
router.get('/:id', requireAccess({ roles: ['admin', 'manager'], permission: 'branches:read' }), (req, res, next) =>
  companiesController.findById(req, res, next)
);

// Create company (admin only)
router.post('/', requireAccess({ roles: ['admin'], permission: 'branches:create' }), (req, res, next) =>
  companiesController.create(req, res, next)
);

// Update company (admin only)
router.put('/:id', requireAccess({ roles: ['admin'], permission: 'branches:update' }), (req, res, next) =>
  companiesController.update(req, res, next)
);

// Delete company (admin only)
router.delete('/:id', requireAccess({ roles: ['admin'], permission: 'branches:delete' }), (req, res, next) =>
  companiesController.delete(req, res, next)
);

// Get users assigned to company
router.get('/:id/users', requireAccess({ roles: ['admin', 'manager'], permission: 'users:read' }), (req, res, next) =>
  companiesController.getUsers(req, res, next)
);

// Get subsidiaries (child companies)
router.get('/:id/subsidiaries', requireAccess({ roles: ['admin', 'manager'], permission: 'branches:read' }), (req, res, next) =>
  companiesController.getSubsidiaries(req, res, next)
);

export default router;
