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

/**
 * Dev-mode transport that pipes log records to the browser/Node console.
 * Each record is printed as `[LEVEL] ts msg {fields}`.
 */
export class ConsoleTransport implements LogTransport {
  write(record: LogRecord): void {
    const prefix = `[${record.level.toUpperCase()}] ${record.ts}`;
    const hasFields = Object.keys(record.fields).length > 0;
    const msg = hasFields
      ? `${prefix} ${record.msg} ${JSON.stringify(record.fields)}`
      : `${prefix} ${record.msg}`;

    switch (record.level) {
      case "debug":
        // eslint-disable-next-line no-console
        console.debug(msg);
        break;
      case "info":
        // eslint-disable-next-line no-console
        console.info(msg);
        break;
      case "warn":
        console.warn(msg);
        break;
      case "error":
        console.error(msg);
        break;
    }
  }

  async flush(): Promise<void> {
    // Console output is synchronous — nothing to flush.
  }
}
