import fs from 'node:fs';
import path from 'node:path';

const ORDER_LOG_FILE = process.env.ORDER_LOG_FILE || path.join('logs', 'orders.log');

fs.mkdirSync(path.dirname(ORDER_LOG_FILE), { recursive: true });
const stream = fs.createWriteStream(ORDER_LOG_FILE, { flags: 'a' });

let orderSequence = 0;

export function logOrder(order) {
  orderSequence += 1;
  const externalId = order?.externalId ?? '';

  const line = `${new Date().toISOString()} #${orderSequence} externalId=${externalId} ${JSON.stringify(order)}\n`;
  stream.write(line);
}

export function closeOrderLog() {
  stream.end();
}
