/**
* REST Handler — Negotiate
* Handles /ucp/v1/negotiate routes for capability negotiation.
* Uses getDeps() for shared config and Zod for input validation.
*/
import type { RESTRequest, RESTResponse } from './types.js';
import { ok, badRequest, methodNotAllowed, serverError } from './types.js';
import { negotiateTerms } from '../tools/negotiate-terms.js';
import { getDeps } from '../dynamo/factory.js';
import { negotiateSchema } from './schemas.js';
// ─── Handler ───
export async function handleNegotiate(req: RESTRequest): Promise<RESTResponse> {
if (req.method !== 'POST') {
return methodNotAllowed(['POST']);
}
const parsed = negotiateSchema.safeParse(req.body);
if (!parsed.success) {
const msg = parsed.error.issues.map((i) => i.message).join('; ');
return badRequest(msg);
}
try {
const { config } = getDeps();
const result = await negotiateTerms(
{
cart_id: parsed.data.cart_id,
agent_profile_url: parsed.data.agent_profile_url,
discount_code: parsed.data.discount_code,
},
config,
);
return ok(result);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
return serverError(message);
}
}