type LogLevel = "log" | "info" | "warn" | "error";

interface LogEntry {
  level: LogLevel;
  message: unknown[];
  timestamp: string;
}

class LogCollector {
  private logs: LogEntry[] = [];
  private originalConsole: Partial<
    Record<LogLevel, (..._args: unknown[]) => void>
  > = {};

  constructor() {
    (["log", "info", "warn", "error"] as LogLevel[]).forEach((level) => {
      // eslint-disable-next-line no-console
      this.originalConsole[level] = console[level];
      // eslint-disable-next-line no-console
      console[level] = (..._args: unknown[]) => {
        this.logs.push({
          level,
          message: _args,
          timestamp: new Date().toISOString(),
        });
        this.originalConsole[level]?.apply(console, _args);
      };
    });
  }

  getLogs(): string {
    return this.logs
      .map(
        (entry) =>
          `[${entry.timestamp}] [${entry.level.toUpperCase()}] ${entry.message
            .map((m) => (typeof m === "object" ? JSON.stringify(m) : String(m)))
            .join(" ")}`,
      )
      .join("\n");
  }

  clear() {
    this.logs = [];
  }
}

export const logCollector = new LogCollector();
