// packages/core-shared/src/instrumentation/sentry/sentry-logger.ts
import * as Sentry from "@sentry/nextjs";
import type { ILogger, Breadcrumb, CaptureContext } from "../logger.interface";
import { isReported, markReported } from "../reported-flag";

export class SentryLogger implements ILogger {
  captureException(err: unknown, ctx?: CaptureContext): void {
    if (isReported(err)) return;
    Sentry.captureException(err, ctx);
    markReported(err);
  }

  captureMessage(
    msg: string,
    level: "info" | "warning" | "error" = "info",
    ctx?: CaptureContext,
  ): void {
    Sentry.captureMessage(msg, { level, ...ctx });
  }

  addBreadcrumb(b: Breadcrumb): void {
    Sentry.addBreadcrumb({
      category: b.category,
      message: b.message,
      level: b.level,
      data: b.data,
    });
  }

  setUser(user: { id: string } | null): void {
    if (user === null) {
      Sentry.setUser(null);
      return;
    }
    const { id, ...extra } = user as { id: string } & Record<string, unknown>;
    if (Object.keys(extra).length > 0) {
      // R36 — strip non-id keys; warn in dev for visibility
      console.warn(
        "[SentryLogger.setUser] stripped non-id keys for PII safety:",
        Object.keys(extra),
      );
    }
    Sentry.setUser({ id });
  }
}
