/**
* REST Handler — Catalog
* Handles /ucp/v1/catalog routes for product search and retrieval.
*/
import type { RESTRequest, RESTResponse } from './types.js';
import { ok, notFound, badRequest, methodNotAllowed, serverError } from './types.js';
import { scoutInventory } from '../tools/scout-inventory.js';
export async function handleCatalog(req: RESTRequest): Promise<RESTResponse> {
if (req.method !== 'GET') {
return methodNotAllowed(['GET']);
}
// GET /ucp/v1/catalog/{productId}
if (req.segments.length > 0) {
const productId = req.segments[0];
return notFound(`Product ${productId} not found`);
}
// GET /ucp/v1/catalog
const query = req.query.q;
if (!query) {
return badRequest('q is required');
}
const params: {
query: string;
category?: string;
price_min?: number;
price_max?: number;
limit?: number;
} = { query };
if (req.query.category) {
params.category = req.query.category;
}
if (req.query.price_min) {
params.price_min = parseInt(req.query.price_min, 10);
}
if (req.query.price_max) {
params.price_max = parseInt(req.query.price_max, 10);
}
if (req.query.limit) {
params.limit = parseInt(req.query.limit, 10);
}
try {
const result = await scoutInventory(params);
return ok(result);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
return serverError(message);
}
}