import type { Logger, LogFields, LogLevel, LogRecord, LogTransport } from "./types.js";

export class LoggerImpl implements Logger {
  private readonly transport: LogTransport;
  private readonly context: LogFields;

  constructor(transport: LogTransport, context: LogFields = {}) {
    this.transport = transport;
    this.context = context;
  }

  debug(msg: string, fields?: LogFields): void {
    this.write("debug", msg, fields);
  }

  info(msg: string, fields?: LogFields): void {
    this.write("info", msg, fields);
  }

  warn(msg: string, fields?: LogFields): void {
    this.write("warn", msg, fields);
  }

  error(msg: string, fields?: LogFields & { err?: Error }): void {
    const { err, ...rest } = fields ?? {};
    const serialized: LogFields = { ...rest };
    if (err) {
      serialized["err"] = `${err.name}: ${err.message}`;
    }
    this.write("error", msg, serialized);
  }

  child(context: LogFields): Logger {
    return new LoggerImpl(this.transport, { ...this.context, ...context });
  }

  private write(level: LogLevel, msg: string, fields?: LogFields): void {
    const record: LogRecord = {
      ts: new Date().toISOString(),
      level,
      msg,
      fields: { ...this.context, ...fields },
    };
    this.transport.write(record);
  }
}
