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

import util from "node:util";
import { Writable } from "node:stream";

import dayjs from "dayjs";

import { GadgetLogLevel } from "./log.ts";
import { GadgetLogTransport } from "./log-transport.ts";
import { GadgetComponent } from "./component.ts";

export class GadgetLogTransportFile implements GadgetLogTransport {
  file: Writable;

  constructor(file: Writable) {
    this.file = file;
  }

  async writeLog(
    timestamp: Date,
    component: GadgetComponent,
    level: GadgetLogLevel,
    message: string,
    metadata?: unknown,
  ): Promise<void> {
    return new Promise<void>((resolve, reject) => {
      const stimestamp = dayjs(timestamp).format("YYYY-MM-DD HH:mm:ss.SSS");

      let sLogMessage = `${stimestamp} ${level} ${component.slug} ${message}`;
      if (metadata) {
        sLogMessage += " " + util.inspect(metadata, false, Infinity, false);
      }

      const chunk = Buffer.from(sLogMessage + "\n");
      this.file.write(chunk, (error: Error | null | undefined): void => {
        if (error) {
          return reject(error);
        }
        return resolve();
      });
    });
  }
}
