import crypto from 'node:crypto';

export function createRequestId(existing) {
  if (typeof existing === 'string' && existing.trim()) return existing.trim();
  return `req_${crypto.randomUUID()}`;
}

export function attachRequestId(req, res, next) {
  const requestId = createRequestId(req.get('x-request-id'));
  req.requestId = requestId;
  res.setHeader('X-Request-Id', requestId);
  next();
}

export function sendJson(res, req, status, body) {
  const requestId = req?.requestId ?? createRequestId();
  return res.status(status).json({ ...body, request_id: requestId });
}

export function sendData(res, req, data, status = 200) {
  return sendJson(res, req, status, { data });
}

export function sendError(res, req, status, code, message, details) {
  return sendJson(res, req, status, {
    error: {
      code,
      message,
      ...(details ? { details } : {}),
    },
  });
}
