import { Router } from 'express';
import { asyncHandler } from '../../middleware/asyncHandler';
import { authenticate } from '../../middleware/authenticate';
import { requireFeature } from '../../middleware/requireFeature';
import { requirePermission } from '../../middleware/requirePermission';
import { authorize } from '../../middleware/authorize';
import { Role } from '@prisma/client';
import * as ctrl from './subadmin.controller';

export const subAdminRouter = Router();

// Staff management needs MANAGE_STAFF (Hostel Admin by default; a delegated
// custom role could also grant it).
// Ahead of the MANAGE_STAFF gate: a staff member replacing their own photo
// is not managing staff, and a warden holds no such permission. It is scoped
// by the session, so it can only ever reach their own row.
subAdminRouter.patch(
  '/me/photo',
  authenticate,
  authorize(Role.HOSTEL_ADMIN, Role.WARDEN, Role.MESS_ADMIN),
  asyncHandler(ctrl.updateMyStaffPhoto),
);

subAdminRouter.use(authenticate, requirePermission('MANAGE_STAFF'));

subAdminRouter.post('/', asyncHandler(ctrl.createSubAdmin));
// Literal path before any param route, so it is not swallowed.
subAdminRouter.get('/stats', asyncHandler(ctrl.subAdminStats));
subAdminRouter.get('/salary-run', requireFeature('expenses'), asyncHandler(ctrl.salaryRunPreview));
subAdminRouter.post('/salary-run', requireFeature('expenses'), asyncHandler(ctrl.salaryRunPost));
subAdminRouter.get('/', asyncHandler(ctrl.listSubAdmins));
subAdminRouter.get('/:id', asyncHandler(ctrl.getSubAdmin));
subAdminRouter.patch('/:id', asyncHandler(ctrl.updateSubAdmin));
subAdminRouter.patch('/:id/role', asyncHandler(ctrl.assignRole));
subAdminRouter.post('/:id/reset-password', asyncHandler(ctrl.resetSubAdminPassword));
subAdminRouter.delete('/:id', asyncHandler(ctrl.deleteSubAdmin));
