// packages/core-shared/src/instrumentation/sentry/init-client-react.test.ts
import { describe, it, expect, vi, beforeEach } from "vitest";

const { replayIntegration } = vi.hoisted(() => {
  const replayIntegration = vi.fn((opts: unknown) => ({ name: "Replay", _opts: opts }));
  return { replayIntegration };
});

vi.mock("@sentry/react", () => ({
  init: vi.fn(),
  replayIntegration,
}));

import * as SentryReact from "@sentry/react";
import { initSentryClientReact } from "@/instrumentation/sentry/init-client-react";

describe("initSentryClientReact", () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it("calls SentryReact.init with sendDefaultPii: false (R31)", () => {
    initSentryClientReact({ dsn: "https://x@y/1", app: "web-tanstack" });
    const call = (SentryReact.init as ReturnType<typeof vi.fn>).mock.calls[0]![0] as Record<
      string,
      unknown
    >;
    expect(call["sendDefaultPii"]).toBe(false);
  });

  it("attaches replay integration with mask flags (R34, R35)", () => {
    initSentryClientReact({ dsn: "https://x@y/1", app: "web-tanstack" });
    expect(replayIntegration).toHaveBeenCalledTimes(1);
    const replayOpts = (replayIntegration as ReturnType<typeof vi.fn>).mock.calls[0]![0] as Record<
      string,
      unknown
    >;
    expect(replayOpts["maskAllText"]).toBe(true);
    expect(replayOpts["maskAllInputs"]).toBe(true);
    expect(replayOpts["blockAllMedia"]).toBe(true);
  });

  it("defaults replay sample rates per R37", () => {
    initSentryClientReact({ dsn: "https://x@y/1", app: "web-tanstack" });
    const call = (SentryReact.init as ReturnType<typeof vi.fn>).mock.calls[0]![0] as Record<
      string,
      unknown
    >;
    expect(call["replaysSessionSampleRate"]).toBe(0.0);
    expect(call["replaysOnErrorSampleRate"]).toBe(1.0);
  });

  it("attaches beforeSend + beforeSendTransaction scrubbers", () => {
    initSentryClientReact({ dsn: "https://x@y/1", app: "web-tanstack" });
    const call = (SentryReact.init as ReturnType<typeof vi.fn>).mock.calls[0]![0] as Record<
      string,
      unknown
    >;
    expect(typeof call["beforeSend"]).toBe("function");
    expect(typeof call["beforeSendTransaction"]).toBe("function");
  });

  it("is a no-op when dsn is missing", () => {
    initSentryClientReact({ dsn: "", app: "web-tanstack" });
    expect(SentryReact.init).not.toHaveBeenCalled();
  });
});
