import type { FastifyInstance } from 'fastify';
import {
  listHandler, getHandler, createHandler, updateHandler, deleteHandler,
  addSealHandler, removeSealHandler,
} from '../controllers/client.controller.js';
import { authorize, authorizeAny } from '../plugins/authorize.js';
import { PERMISSIONS } from '../constants/permissions.js';
import { createClientSchema, updateClientSchema, addSealSchema } from '../schemas/client.schema.js';

// Picking a client to attach to an order (or to filter a report by) requires
// browsing the client list, so order and report permissions also unlock
// these browse endpoints.
const CAN_BROWSE_CLIENTS = [
  PERMISSIONS.CLIENTS_VIEW, PERMISSIONS.ORDERS_VIEW, PERMISSIONS.ORDERS_CREATE, PERMISSIONS.ORDERS_EDIT,
  PERMISSIONS.REPORTS_VIEW,
];

export default async function clientRoutes(fastify: FastifyInstance) {
  fastify.get('/api/clients', { preHandler: [authorizeAny(CAN_BROWSE_CLIENTS)] }, listHandler);
  fastify.get('/api/clients/:id', { preHandler: [authorizeAny(CAN_BROWSE_CLIENTS)] }, getHandler);
  fastify.post('/api/clients', { preHandler: [authorize(PERMISSIONS.CLIENTS_CREATE)], schema: createClientSchema }, createHandler);
  fastify.put('/api/clients/:id', { preHandler: [authorize(PERMISSIONS.CLIENTS_EDIT)], schema: updateClientSchema }, updateHandler);
  fastify.delete('/api/clients/:id', { preHandler: [authorize(PERMISSIONS.CLIENTS_DELETE)] }, deleteHandler);
  fastify.post('/api/clients/:id/seals', { preHandler: [authorize(PERMISSIONS.CLIENTS_EDIT)], schema: addSealSchema }, addSealHandler);
  fastify.delete('/api/clients/:clientId/seals/:sealId', { preHandler: [authorize(PERMISSIONS.CLIENTS_EDIT)] }, removeSealHandler);
}
