import type { FastifyInstance } from 'fastify';
import { searchHandler } from '../controllers/search.controller.js';
import { authorizeAny } from '../plugins/authorize.js';
import { PERMISSIONS } from '../constants/permissions.js';

// ORDERS_STAGE_UPDATE alone (no ORDERS_VIEW) also unlocks the full Orders
// page today (see order.routes.ts's CAN_BROWSE_ORDERS), so allowing it here
// too is consistent — but unlike that route, search.service.ts scopes an
// ORDERS_STAGE_UPDATE-only employee's results down to their own assigned
// stages when they have any (see its isUnrestricted check), rather than
// handing back the unrestricted result set every other caller gets.
// ORDERS_RETURN_REQUEST also unlocks this endpoint — a requester who can
// raise returns but has no other search/order permission still needs to hit
// the delivered-only (?delivered=true) search to find the line to return.
const CAN_SEARCH = [PERMISSIONS.ORDERS_VIEW, PERMISSIONS.ORDERS_STAGE_UPDATE, PERMISSIONS.ORDERS_RETURN_REQUEST, PERMISSIONS.ORDERS_RETURN_APPROVE];

export default async function searchRoutes(fastify: FastifyInstance) {
  fastify.get('/api/search', { preHandler: [authorizeAny(CAN_SEARCH)] }, searchHandler);
}
