import { pino, type Logger as PinoLogger } from "pino";
import type { LoggerService } from "./logger-service";
import { config } from "../../config";

export class PinoLoggerService implements LoggerService {
  private logger: PinoLogger;

  constructor(name?: string, parent?: PinoLogger) {
    if (parent) {
      this.logger = parent.child({ name });
    } else {
      const useTransport =
        config.isDevelopment && typeof window === "undefined";

      this.logger = pino({
        name: name || "app",
        level: config.logging.level,
        transport: useTransport
          ? {
              target: "pino-pretty",
              options: {
                colorize: true,
              },
            }
          : undefined,
      });
    }
  }

  debug(message: string, context?: Record<string, unknown>) {
    if (context) this.logger.debug(context, message);
    else this.logger.debug(message);
  }

  info(message: string, context?: Record<string, unknown>) {
    if (context) this.logger.info(context, message);
    else this.logger.info(message);
  }

  warn(message: string, context?: Record<string, unknown>) {
    if (context) this.logger.warn(context, message);
    else this.logger.warn(message);
  }

  error(message: string, context?: Record<string, unknown>) {
    if (context) this.logger.error(context, message);
    else this.logger.error(message);
  }

  child(context: Record<string, unknown>): LoggerService {
    const childPino = this.logger.child(context);
    const service = new PinoLoggerService();
    service.logger = childPino;
    return service;
  }
}
