import { Global, Module } from "@nestjs/common";
import { LoggerModule } from "nestjs-pino";

@Global()
@Module({
  imports: [
    LoggerModule.forRoot({
      pinoHttp: {
        level: process.env.LOG_LEVEL || "info",
        name: process.env.APP_NAME || "customer-portal-bff",
        autoLogging: {
          ignore: req => {
            const url = req.url || "";
            return (
              url.includes("/health") ||
              url.includes("/favicon") ||
              url.includes("/_next/") ||
              url.includes("/api/auth/session")
            );
          },
        },
        serializers: {
          req: (req: { method?: string; url?: string; headers?: Record<string, unknown> }) => ({
            method: req.method,
            url: req.url,
            ...(process.env.NODE_ENV === "development" && {
              headers: req.headers,
            }),
          }),
          res: (res: { statusCode?: number }) => ({
            statusCode: res.statusCode,
          }),
        },
        transport:
          process.env.NODE_ENV === "development"
            ? {
                target: "pino-pretty",
                options: {
                  colorize: true,
                  translateTime: "yyyy-mm-dd HH:MM:ss",
                  ignore: "pid,hostname,req,res",
                  messageFormat: "{msg}",
                },
              }
            : undefined,
        redact: {
          paths: [
            "req.headers.authorization",
            "req.headers.cookie",
            "req.body",
            "res.body",
            "password",
            "token",
            "secret",
            "jwt",
            "apiKey",
          ],
          remove: true,
        },
        formatters: {
          level: (label: string) => ({ level: label }),
          bindings: () => ({}),
        },
      },
    }),
  ],
  exports: [LoggerModule],
})
export class LoggingModule {}
