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

import { Writable } from "node:stream";

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

export class DtpLogTransportFile implements DtpLogTransport {
  file: Writable;

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

  async writeLog(
    timestamp: Date,
    component: DtpComponent,
    level: DtpLogLevel,
    message: string,
    metadata?: unknown
  ): Promise<void> {
    return new Promise<void>((resolve, reject) => {
      const logMessage = JSON.stringify({
        timestamp,
        component,
        level,
        message,
        metadata,
      });
      const chunk = Buffer.from(logMessage + "\r\n");
      this.file.write(chunk, (error: Error | null | undefined): void => {
        if (error) {
          return reject(error);
        }
        return resolve();
      });
    });
  }
}
