import { afterEach, describe, expect, it, vi } from "vitest"

import { logger } from "../logger"

/**
 * Tests for the logger facade (KAR-535).
 *
 * Verifies that the SENSITIVE_KEYS scrubbing fires on the PII field names
 * extended by KAR-535. We spy on console.log/warn/error because the
 * facade routes through there.
 */

let logSpy: ReturnType<typeof vi.spyOn>

afterEach(() => {
  logSpy?.mockRestore()
})

function capture(): { lines: string[] } {
  const lines: string[] = []
  logSpy = vi
    .spyOn(console, "log")
    .mockImplementation(((line: string) => {
      lines.push(line)
    }) as never)
  return { lines }
}

describe("logger PII redaction (KAR-535)", () => {
  it.each([
    "password",
    "token",
    "email",
    "user_email",
    "first_name",
    "last_name",
    "full_name",
    "display_name",
    "phone",
    "phone_number",
    "iban",
    "tax_id",
    "ssn",
    "date_of_birth",
    "address",
  ])("redacts %s field value", (key) => {
    const { lines } = capture()
    logger.info("pii.test", { [key]: "should-not-appear" })
    const joined = lines.join("\n")
    expect(joined).toContain("[REDACTED]")
    expect(joined).not.toContain("should-not-appear")
  })

  it("does NOT redact safe identifiers like user_id", () => {
    const { lines } = capture()
    logger.info("safe.test", { user_id: "uuid-1234" })
    const joined = lines.join("\n")
    expect(joined).toContain("uuid-1234")
  })
})
