import type { FastifyInstance } from 'fastify';
import { listHandler, createHandler, updateHandler, reorderHandler, deleteHandler } from '../controllers/stage.controller.js';
import { authorize, authorizeAny } from '../plugins/authorize.js';
import { PERMISSIONS } from '../constants/permissions.js';
import { createStageSchema, updateStageSchema, reorderStageSchema } from '../schemas/stage.schema.js';

// Stages back the production progress dropdown on every order line, so
// anyone who can view/create/edit orders needs to be able to list them —
// same reasoning as wireSize.routes.ts's CAN_BROWSE_PRODUCTS. An employee
// restricted to ORDERS_STAGE_UPDATE alone (no ORDERS_VIEW/EDIT) still needs
// this to render their own stage dropdown at all — without it the list
// comes back empty and every position lookup silently misresolves to 0
// ("Not Started"), which is exactly the bug this fixes.
const CAN_BROWSE_STAGES = [
  PERMISSIONS.STAGES_VIEW, PERMISSIONS.ORDERS_VIEW, PERMISSIONS.ORDERS_CREATE, PERMISSIONS.ORDERS_EDIT,
  PERMISSIONS.ORDERS_STAGE_UPDATE,
];

export default async function stageRoutes(fastify: FastifyInstance) {
  fastify.get('/api/stages', { preHandler: [authorizeAny(CAN_BROWSE_STAGES)] }, listHandler);
  fastify.post('/api/stages', { preHandler: [authorize(PERMISSIONS.STAGES_CREATE)], schema: createStageSchema }, createHandler);
  fastify.put('/api/stages/:id', { preHandler: [authorize(PERMISSIONS.STAGES_EDIT)], schema: updateStageSchema }, updateHandler);
  fastify.put('/api/stages/reorder', { preHandler: [authorize(PERMISSIONS.STAGES_EDIT)], schema: reorderStageSchema }, reorderHandler);
  fastify.delete('/api/stages/:id', { preHandler: [authorize(PERMISSIONS.STAGES_DELETE)] }, deleteHandler);
}
