/**
 * src/server/response.ts — HTTP response helpers for Planu HTTP API
 *
 * SPEC-610: Unified JSON response format with CORS headers.
 */
/** Set common headers (Content-Type + CORS) on every response. */
function setCommonHeaders(res) {
    res.setHeader('Content-Type', 'application/json');
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PATCH, OPTIONS');
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
}
/** Send a success JSON response. */
export function sendOk(res, data, status = 200) {
    setCommonHeaders(res);
    const body = { data, error: null };
    res.writeHead(status);
    res.end(JSON.stringify(body));
}
/** Send a 400 Bad Request error. */
export function sendBadRequest(res, message) {
    setCommonHeaders(res);
    const body = { data: null, error: { message, code: 'BAD_REQUEST' } };
    res.writeHead(400);
    res.end(JSON.stringify(body));
}
/** Send a 404 Not Found error. */
export function sendNotFound(res, message) {
    setCommonHeaders(res);
    const body = { data: null, error: { message, code: 'NOT_FOUND' } };
    res.writeHead(404);
    res.end(JSON.stringify(body));
}
/** Send a 500 Internal Server Error. */
export function sendInternalError(res, message) {
    setCommonHeaders(res);
    const body = { data: null, error: { message, code: 'INTERNAL_ERROR' } };
    res.writeHead(500);
    res.end(JSON.stringify(body));
}
/**
 * Read and parse the JSON request body.
 * Returns parsed object or throws on malformed JSON or non-object body.
 */
export async function readBody(req) {
    return new Promise((resolve, reject) => {
        const chunks = [];
        req.on('data', (chunk) => {
            chunks.push(chunk);
        });
        req.on('end', () => {
            const raw = Buffer.concat(chunks).toString('utf-8');
            if (!raw.trim()) {
                resolve({});
                return;
            }
            try {
                const parsed = JSON.parse(raw);
                resolve(parsed);
            }
            catch {
                reject(new Error('Invalid JSON body'));
            }
        });
        req.on('error', reject);
    });
}
//# sourceMappingURL=response.js.map