'use strict';
const fs = require('fs');
const path = require('path');

/**
 * Atomic file write using tmp + rename (POSIX rename is atomic on same filesystem).
 * Prevents read-modify-write races when multiple sessions write to .env concurrently.
 */
function atomicWriteFileSync(filePath, data, options) {
  const resolved = path.resolve(filePath);
  const tmp = resolved + '.tmp.' + process.pid + '.' + Date.now();
  try {
    fs.writeFileSync(tmp, data, options);
    fs.renameSync(tmp, resolved);
  } catch (e) {
    // Clean up tmp file on failure
    try { fs.unlinkSync(tmp); } catch {}
    throw e;
  }
}

module.exports = { atomicWriteFileSync };
