// src/lib/log.ts
// Copyright (C) 2026 Rob Colbert <rob.colbert@openplatform.us>
// Licensed under the Apache License, Version 2.0

import env from "../config/env.js";

import { GadgetComponent } from "./component.ts";
import { GadgetLogTransportConsole } from "./log-transport-console.js";
import { GadgetLogTransportFile } from "./log-transport-file.js";
import { GadgetLogTransport } from "./log-transport.js";
import { GadgetLogFile, defaultLogFile } from "./log-file.js";

export enum GadgetLogLevel {
  debug = "debug",
  info = "info",
  warn = "warn",
  alert = "alert",
  error = "error",
  crit = "crit",
  fatal = "fatal",
}

export class GadgetLog {
  component: GadgetComponent;
  transports: GadgetLogTransport[] = [];

  private static defaultTransports: GadgetLogTransport[] = [];
  private file: GadgetLogFile;

  constructor(component: GadgetComponent, file?: GadgetLogFile) {
    this.component = component;
    this.file = file || defaultLogFile;
    this.transports.push(...GadgetLog.defaultTransports);

    if (env.log.console.enabled) {
      this.transports.push(new GadgetLogTransportConsole());
    }
    if (env.log.file.enabled) {
      this.transports.push(new GadgetLogTransportFile(this.file));
    }
  }

  public static addDefaultTransport(transport: GadgetLogTransport): void {
    GadgetLog.defaultTransports.push(transport);
  }

  public static removeDefaultTransport(transport: GadgetLogTransport): void {
    const index = GadgetLog.defaultTransports.indexOf(transport);
    if (index > -1) {
      GadgetLog.defaultTransports.splice(index, 1);
    }
  }

  public static getDefaultTransports(): GadgetLogTransport[] {
    return GadgetLog.defaultTransports;
  }

  async debug(message: string, metadata?: unknown) {
    if (!env.log.levels.debug) {
      return;
    }
    return this.writeLog(GadgetLogLevel.debug, message, metadata);
  }

  async info(message: string, metadata?: unknown) {
    if (!env.log.levels.info) {
      return;
    }
    return this.writeLog(GadgetLogLevel.info, message, metadata);
  }

  async warn(message: string, metadata?: unknown) {
    if (!env.log.levels.warn) {
      return;
    }
    return this.writeLog(GadgetLogLevel.warn, message, metadata);
  }

  async alert(message: string, metadata?: unknown) {
    return this.writeLog(GadgetLogLevel.alert, message, metadata);
  }

  async error(message: string, metadata?: unknown) {
    return this.writeLog(GadgetLogLevel.error, message, metadata);
  }

  async crit(message: string, metadata?: unknown) {
    return this.writeLog(GadgetLogLevel.crit, message, metadata);
  }

  async fatal(message: string, metadata?: unknown) {
    this.writeLog(GadgetLogLevel.fatal, message, metadata);
  }

  async writeLog(level: GadgetLogLevel, message: string, metadata?: unknown) {
    const NOW = new Date();
    for (const transport of this.transports) {
      transport.writeLog(NOW, this.component, level, message, metadata);
    }
  }
}
