import { __esmMin } from "../../../_virtual/_rolldown/runtime.js";
import { getLogDir, init_config } from "./config.js";
import { appendFile } from "fs/promises";
import path from "path";
import { existsSync, mkdirSync } from "fs";
//#region src/utils/logger/audit.ts
/**
* Audit Log
* 
* Independent audit log stream for security-sensitive events:
* - Authentication events (login, logout, token refresh)
* - Configuration changes
* - Permission changes
* - Data access events
*/
function configureAuditLog(config) {
	auditConfig = {
		...auditConfig,
		...config
	};
}
function getAuditConfig() {
	return { ...auditConfig };
}
function generateEventId() {
	const timestamp = Date.now().toString(36);
	const random = Math.random().toString(36).substring(2, 8);
	return `audit_${timestamp}_${(++seq).toString(36).padStart(4, "0")}_${random}`;
}
function redactSensitiveData(data) {
	if (!auditConfig.sensitiveFields) return data;
	const redacted = {};
	for (const [key, value] of Object.entries(data)) if (auditConfig.sensitiveFields.some((field) => key.toLowerCase().includes(field.toLowerCase()))) redacted[key] = "***REDACTED***";
	else if (value && typeof value === "object" && !Array.isArray(value)) redacted[key] = redactSensitiveData(value);
	else if (Array.isArray(value)) redacted[key] = value.map((item) => item && typeof item === "object" ? redactSensitiveData(item) : item);
	else redacted[key] = value;
	return redacted;
}
/**
* Redact sensitive fields from an audit event before writing
*/
function redactEvent(event) {
	const redactedEvent = { ...event };
	if (redactedEvent.actor) redactedEvent.actor = { ...redactSensitiveData(redactedEvent.actor) };
	if (redactedEvent.action?.details) redactedEvent.action = {
		...redactedEvent.action,
		details: redactSensitiveData(redactedEvent.action.details)
	};
	if (redactedEvent.resource) redactedEvent.resource = { ...redactSensitiveData(redactedEvent.resource) };
	if (redactedEvent.metadata) redactedEvent.metadata = { ...redactSensitiveData(redactedEvent.metadata) };
	return redactedEvent;
}
function getAuditLogPath(date = /* @__PURE__ */ new Date()) {
	const dateStr = date.toISOString().split("T")[0];
	const logDir = auditConfig.logDir || path.join(getLogDir(), "audit");
	if (!existsSync(logDir)) mkdirSync(logDir, { recursive: true });
	return path.join(logDir, `audit-${dateStr}.log`);
}
async function writeAuditEvent(event) {
	if (!auditConfig.enabled) return;
	const redactedEvent = redactEvent(event);
	const logLine = JSON.stringify(redactedEvent) + "\n";
	const logPath = getAuditLogPath();
	try {
		await appendFile(logPath, logLine, "utf-8");
		if (auditConfig.logToConsole) console.log(`[AUDIT] ${event.type}: ${event.action.type} by ${event.actor.userId || "anonymous"}`);
	} catch (err) {
		console.error("[AuditLog] Failed to write audit event:", err);
	}
}
async function logAuditEvent(type, params) {
	const event = {
		id: generateEventId(),
		timestamp: (/* @__PURE__ */ new Date()).toISOString(),
		type,
		actor: params.actor || {},
		resource: params.resource,
		action: {
			result: "success",
			...params.action
		},
		metadata: params.metadata
	};
	await writeAuditEvent(event);
	return event;
}
async function logAuthEvent(type, params) {
	return logAuditEvent(type, {
		actor: {
			userId: params.userId,
			sessionId: params.sessionId,
			ip: params.ip,
			userAgent: params.userAgent
		},
		resource: { type: "auth" },
		action: {
			type: type.split(".")[1],
			result: params.result,
			details: params.reason ? { reason: params.reason } : void 0
		}
	});
}
async function logConfigChange(params) {
	return logAuditEvent("config.update", {
		actor: { userId: params.userId },
		resource: {
			type: "config",
			id: params.section,
			path: params.path
		},
		action: {
			type: "update",
			result: params.result,
			details: {
				oldValue: params.oldValue,
				newValue: params.newValue
			}
		}
	});
}
async function logPermissionChange(params) {
	return logAuditEvent(params.action === "grant" ? "permission.grant" : "permission.revoke", {
		actor: { userId: params.userId },
		resource: {
			type: params.resourceType,
			id: params.resourceId
		},
		action: {
			type: params.action,
			result: params.result,
			details: {
				targetUserId: params.targetUserId,
				permission: params.permission
			}
		}
	});
}
async function logDataAccess(params) {
	return logAuditEvent({
		read: "data.access",
		write: "data.access",
		delete: "data.delete",
		export: "data.export"
	}[params.action], {
		actor: {
			userId: params.userId,
			sessionId: params.sessionId
		},
		resource: {
			type: params.resourceType,
			id: params.resourceId,
			path: params.path
		},
		action: {
			type: params.action,
			result: params.result,
			details: params.metadata
		}
	});
}
var auditConfig, seq;
var init_audit = __esmMin((() => {
	init_config();
	auditConfig = {
		enabled: true,
		retentionDays: 90,
		logToConsole: false,
		sensitiveFields: [
			"password",
			"token",
			"apiKey",
			"secret",
			"credential",
			"authorization",
			"cookie",
			"session"
		]
	};
	seq = 0;
}));
//#endregion
init_audit();
export { configureAuditLog, getAuditConfig, init_audit, logAuditEvent, logAuthEvent, logConfigChange, logDataAccess, logPermissionChange };

//# sourceMappingURL=audit.js.map