import fs from "node:fs/promises";
import { randomUUID } from "node:crypto";
import pino from "pino";
import { config } from "../config"
import { AuditLog } from "../types"

export const logger = pino({
  level: process.env.LOG_LEVEL ?? "info",
});

export const appendAuditLog = async (
  entry: Omit<AuditLog, "id" | "createdAt">
) => {
  const logEntry: AuditLog = {
    id: randomUUID(),
    createdAt: new Date().toISOString(),
    ...entry,
  };
  try {
    let existing: AuditLog[] = [];
    try {
      const content = await fs.readFile(config.logsPath, "utf-8");
      existing = JSON.parse(content) as AuditLog[];
    } catch (error) {
      if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
        throw error;
      }
    }
    const next = [...existing, logEntry].slice(-2000);
    await fs.writeFile(config.logsPath, JSON.stringify(next, null, 2), "utf-8");
  } catch (error) {
    logger.error({ error }, "Failed to append audit log");
  }
};
