// src/lib/log-transport-console.ts
// Copyright (C) 2026 Robert Colbert <rob.colbert@openplatform.us>
// All Rights Reserved

import * as util from "node:util";

import dayjs from "dayjs";
import color from "ansicolor";

import { DtpLogLevel } from "./log.js";
import { DtpLogTransport } from "./log-transport.js";
import { DtpComponent } from "./component.ts";

export class DtpLogTransportConsole implements DtpLogTransport {
  async writeLog(
    timestamp: Date,
    component: DtpComponent,
    level: DtpLogLevel,
    message: string,
    metadata?: unknown
  ): Promise<void> {
    let clevel = level.padEnd(5);
    switch (level) {
      case "debug":
        clevel = color.darkGray(clevel);
        break;
      case "info":
        clevel = color.green(clevel);
        break;
      case "warn":
        clevel = color.yellow(clevel);
        break;
      case "alert":
        clevel = color.red(clevel);
        break;
      case "error":
        clevel = color.bgRed.white(clevel);
        break;
      case "crit":
        clevel = color.bgRed.yellow(clevel);
        break;
      case "fatal":
        clevel = color.bgRed.darkGray(clevel);
        break;
    }

    const ccomponent = color.cyan(component.name);
    const ctimestamp = color.darkGray(
      dayjs(timestamp).format("YYYY-MM-DD HH:mm:ss.SSS")
    );
    const cmessage = color.darkGray(message);

    if (metadata) {
      console.log(
        `${ctimestamp} ${clevel} ${ccomponent} ${cmessage}`,
        util.inspect(metadata, false, Infinity, true)
      );
    } else {
      console.log(`${ctimestamp} ${clevel} ${ccomponent} ${cmessage}`);
    }
  }
}
