import type { FastifyInstance } from 'fastify';
import { listHandler, getHandler, createHandler, updateHandler, deleteHandler } from '../controllers/role.controller.js';
import { authorize, authorizeAny } from '../plugins/authorize.js';
import { PERMISSIONS } from '../constants/permissions.js';
import { createRoleSchema, updateRoleSchema } from '../schemas/role.schema.js';

// The Employees page needs to display/assign roles, so employee permissions
// also unlock browsing the role list.
const CAN_BROWSE_ROLES = [
  PERMISSIONS.ROLES_VIEW, PERMISSIONS.EMPLOYEES_VIEW, PERMISSIONS.EMPLOYEES_CREATE, PERMISSIONS.EMPLOYEES_EDIT,
];

export default async function roleRoutes(fastify: FastifyInstance) {
  fastify.get('/api/roles', { preHandler: [authorizeAny(CAN_BROWSE_ROLES)] }, listHandler);
  fastify.get('/api/roles/:id', { preHandler: [authorizeAny(CAN_BROWSE_ROLES)] }, getHandler);
  fastify.post('/api/roles', { preHandler: [authorize(PERMISSIONS.ROLES_CREATE)], schema: createRoleSchema }, createHandler);
  fastify.put('/api/roles/:id', { preHandler: [authorize(PERMISSIONS.ROLES_EDIT)], schema: updateRoleSchema }, updateHandler);
  fastify.delete('/api/roles/:id', { preHandler: [authorize(PERMISSIONS.ROLES_DELETE)] }, deleteHandler);
}
