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

// Order create/edit needs to pick "taken by"/"dispatched by"/"cancelled by"
// employees, and Reports needs to filter by employee — both unlock browsing
// the employee list.
const CAN_BROWSE_EMPLOYEES = [
  PERMISSIONS.EMPLOYEES_VIEW, PERMISSIONS.ORDERS_VIEW, PERMISSIONS.ORDERS_CREATE, PERMISSIONS.ORDERS_EDIT,
  PERMISSIONS.REPORTS_VIEW,
];

export default async function employeeRoutes(fastify: FastifyInstance) {
  fastify.get('/api/employees', { preHandler: [authorizeAny(CAN_BROWSE_EMPLOYEES)] }, listHandler);
  fastify.get('/api/employees/:id', { preHandler: [authorizeAny(CAN_BROWSE_EMPLOYEES)] }, getHandler);
  fastify.post('/api/employees', { preHandler: [authorize(PERMISSIONS.EMPLOYEES_CREATE)], schema: createEmployeeSchema }, createHandler);
  fastify.put('/api/employees/:id', { preHandler: [authorize(PERMISSIONS.EMPLOYEES_EDIT)], schema: updateEmployeeSchema }, updateHandler);
  fastify.delete('/api/employees/:id', { preHandler: [authorize(PERMISSIONS.EMPLOYEES_DELETE)] }, deleteHandler);
}
