import { Router } from 'express';
import { branchController } from '../controllers/branch.controller';
import { authMiddleware, requireRoles } from '../../../shared/middleware/auth.middleware';
import { tenantMiddleware } from '../../../shared/middleware/tenant.middleware';
import { AuthenticatedRequest } from '../../../shared/types';

const router = Router();

// All routes require tenant and authentication
router.use(tenantMiddleware);
router.use(authMiddleware);

// List routes
router.get('/', (req, res, next) => branchController.list(req as AuthenticatedRequest, res, next));
router.get('/active', (req, res, next) => branchController.listActive(req as AuthenticatedRequest, res, next));
router.get('/nearby', (req, res, next) => branchController.findNearby(req as AuthenticatedRequest, res, next));

// Single branch routes
router.get('/code/:code', (req, res, next) => branchController.getByCode(req as AuthenticatedRequest, res, next));
router.get('/:id', (req, res, next) => branchController.getById(req as AuthenticatedRequest, res, next));
router.get('/:id/stats', (req, res, next) => branchController.getStats(req as AuthenticatedRequest, res, next));

// Admin routes (require manager or admin role)
router.post(
  '/',
  requireRoles('admin', 'manager'),
  (req, res, next) => branchController.create(req as AuthenticatedRequest, res, next)
);

router.put(
  '/:id',
  requireRoles('admin', 'manager'),
  (req, res, next) => branchController.update(req as AuthenticatedRequest, res, next)
);

router.patch(
  '/:id/status',
  requireRoles('admin', 'manager'),
  (req, res, next) => branchController.updateStatus(req as AuthenticatedRequest, res, next)
);

router.delete(
  '/:id',
  requireRoles('admin'),
  (req, res, next) => branchController.delete(req as AuthenticatedRequest, res, next)
);

export default router;
