import { sendJson } from '../http.js';
import { logger } from '../logger.js';
import { logOrder } from '../order-log.js';
import { createOrder } from '../queries/create-order.js';

export const method = 'POST';
export const path = '/v1/order';

function parseBody(buffer) {
  if (!buffer || !buffer.length) {
    return null;
  }
  try {
    return JSON.parse(buffer.toString('utf8'));
  } catch {
    return undefined;
  }
}

function getOrders(body) {
  if (!body || typeof body !== 'object') {
    return [];
  }
  if (Array.isArray(body.orders)) {
    return body.orders;
  }
  return [];
}

export async function handle(req, res) {
  const body = parseBody(req.rawBody);

  if (body === undefined) {
    return sendJson(res, 500, []);
  }

  const orders = getOrders(body);
  const results = [];

  for (const order of orders) {
    logOrder(order);
    const externalOrderId = String(order?.externalId ?? '');

    try {
      const created = await createOrder(order);
      logger.success(`order ${created.orderNumber} (kAuftrag=${created.orderId}) created for externalId=${externalOrderId}`);
      results.push({
        status: 'OK',
        externalOrderId,
        message: '',
      });
    } catch (err) {
      logger.error(`order externalId=${externalOrderId} failed: ${err.message}`);
      results.push({
        status: 'ERROR',
        externalOrderId,
        message: err.message,
      });
    }
  }

  return sendJson(res, 200, results);
}
