import { Archon } from "../Archon.js";
import { EventType, LogOptions, Outcome, Severity } from "../types/logging.js";

/**
 * Log an error that occurs in your application.
 * @param error The error that occurred.
 * @param options Options to include with the log message.
 */
export default async function logError(error: Error, options?: LogOptions): Promise<void> {
    // if no severity is provided, default to error
    if (options === undefined) {
        options = {
            eventType: "error" as EventType,
            outcome: Outcome.FAILURE
        };
    }
    if (options.severity === undefined) {
        options.severity = Severity.ERROR;
    }

    if (options.context === undefined) {
        options.context = `${error.name} - ${error.message}`;
    } else {
        options.context = `${error.name} - ${error.message}: ${options.context}`;
    }

    if (error.stack) options.context += `\n${error.stack}`;

    Archon.request("/logging/log", "POST", { ...options, eventType: "error", source: Archon.getComponentName() })
        .catch((err: Error) => {
            console.error(`Failed to log error: ${err}`);
        });
}