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

const LOG_FILE = process.env.LOG_FILE || path.join('logs', 'requests.log');

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

function isoTimestamp() {
  return new Date().toISOString();
}

export function logRequest({ remoteAddress, method, url, statusCode, durationMs, response }) {
  const line = `${isoTimestamp()} ${remoteAddress} ${method} ${url} ${statusCode} ${durationMs}ms ${response}\n`;
  stream.write(line);
}

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