/**
* REST Handler — Cart
* Handles /ucp/v1/cart routes for cart management.
* Uses Zod schemas for input validation.
*/
import type { RESTRequest, RESTResponse } from './types.js';
import { ok, created, notFound, badRequest, methodNotAllowed, serverError } from './types.js';
import { manageCart } from '../tools/manage-cart.js';
import { addToCartSchema } from './schemas.js';
export async function handleCart(req: RESTRequest): Promise<RESTResponse> {
try {
const { method, segments, body } = req;
// POST /ucp/v1/cart — create a new cart
if (method === 'POST' && segments.length === 0) {
const result = await manageCart({ action: 'create' });
return created(result);
}
// GET /ucp/v1/cart/{cartId} — get cart by ID
if (method === 'GET' && segments.length === 1) {
const result = await manageCart({ action: 'get', cart_id: segments[0] });
return ok(result);
}
// POST /ucp/v1/cart/{cartId}/items — add item to cart
if (method === 'POST' && segments.length === 2 && segments[1] === 'items') {
const parsed = addToCartSchema.safeParse(body);
if (!parsed.success) {
const msg = parsed.error.issues.map((i) => i.message).join('; ');
return badRequest(msg);
}
const result = await manageCart({
action: 'add',
cart_id: segments[0],
variant_id: parsed.data.variant_id,
quantity: parsed.data.quantity,
});
return ok(result);
}
// DELETE /ucp/v1/cart/{cartId}/items/{variantId} — remove item from cart
if (method === 'DELETE' && segments.length === 3 && segments[1] === 'items') {
const result = await manageCart({
action: 'remove',
cart_id: segments[0],
variant_id: segments[2],
});
return ok(result);
}
// Determine allowed methods based on path shape
if (segments.length === 0) {
return methodNotAllowed(['POST']);
}
if (segments.length === 1) {
return methodNotAllowed(['GET']);
}
if (segments.length === 2 && segments[1] === 'items') {
return methodNotAllowed(['POST']);
}
if (segments.length === 3 && segments[1] === 'items') {
return methodNotAllowed(['DELETE']);
}
return badRequest('Invalid cart route');
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
if (message.toLowerCase().includes('not found')) {
return notFound(message);
}
if (message.toLowerCase().includes('required')) {
return badRequest(message);
}
return serverError(message);
}
}