import fs from 'fs/promises'
import path from 'path'

// nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal
const getDataPath = (filename) => {
  const cwd = process.cwd()
  if (cwd.endsWith('.output')) {
    // nosemgrep
    return path.join(cwd, '../server/data', filename)
  }
  // nosemgrep
  return path.join(cwd, 'server/data', filename)
}

const AUDIT_LOG_FILE = getDataPath('audit.log.jsonl')

function safeStr(v, max = 500) {
  return String(v == null ? '' : v).slice(0, max)
}

export async function writeAuditLog(eventType, data = {}) {
  const enabled = (process.env.AUDIT_LOG_ENABLED || 'true').toLowerCase() !== 'false'
  if (!enabled) return

  const entry = {
    ts: new Date().toISOString(),
    type: safeStr(eventType, 100),
    data
  }

  await fs.mkdir(path.dirname(AUDIT_LOG_FILE), { recursive: true })
  await fs.appendFile(AUDIT_LOG_FILE, JSON.stringify(entry) + '\n', 'utf-8')
}


