import type { SimulationFunction } from '@x12i/api-simulator'; import { checkoutBook, LibraryError } from '../state/checkout-ledger.js'; import { members } from '../data/members.js'; /** POST /books/:bookId/checkout { memberId } -- validation, then a state change. */ export const checkout: SimulationFunction = ({ request }) => { const bookId = request.params.bookId ?? ''; const memberId = (request.body as { memberId?: string } | undefined)?.memberId; if (!memberId) { return { status: 400, body: { error: 'MEMBER_ID_REQUIRED', message: 'Request body must include memberId.' } }; } if (!members.some((member) => member.id === memberId)) { return { status: 400, body: { error: 'UNKNOWN_MEMBER', message: `No member with id ${memberId}.` } }; } try { const record = checkoutBook(bookId, memberId); return { status: 201, body: { ...record, status: 'checked-out' } }; } catch (error) { if (error instanceof LibraryError) { return { status: error.status, body: { error: error.code, message: error.message } }; } throw error; } };