import { getServerSession } from "next-auth";
import fs from "fs/promises";

export type AuditLogAction = 'login' | 'changeOwnPassword' | 'requestAlias' | 'deleteAlias' | 'createTempAlias' // Unprivileged
  | 'createApiKey' | 'deleteApiKey'
  | 'createUser' | 'createAlias' | 'approveAlias' | 'deleteAlias'; // Privileged

export type AuditLog = {
  user?: string | null,
  ts: string,
  action: AuditLogAction,
  data?: any,
}

export function auditLog(action: AuditLogAction, data?: any) {
  (async () => {
    try {
      const session = await getServerSession();

      const log: AuditLog = {
        user: session?.user?.email,
        ts: new Date().toISOString(),
        action: action,
        data: data,
      };

      await auditLogRaw(log);
    } catch (e) {
      console.error("Failed to write to log file:", e);
    }
  })();
}

export async function auditLogRaw(log: AuditLog) {
  console.log("Audit event:", log);

  if (process.env.AUDIT_FILE_PATH) {
    await fs.appendFile(
      process.env.AUDIT_FILE_PATH,
      JSON.stringify(log) + "\n",
    );
  }
}
