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

import { withDbSpan, withBusinessSpan, recordBusinessMetric } from "../spans"

/**
 * Tests for the OTel span helpers (KAR-532).
 *
 * The helpers wrap @opentelemetry/api primitives. With no SDK registered
 * (the unit-test mode), the OTel API returns no-op tracers and meters. The
 * tests verify behavioural contracts of our wrappers regardless of whether
 * a real exporter is wired:
 *
 *   - withDbSpan returns the inner function's value on success.
 *   - withDbSpan re-throws the inner function's error.
 *   - withBusinessSpan returns the inner function's value.
 *   - recordBusinessMetric does not throw when called.
 *
 * End-to-end span/attribute assertions are owned by the OTel SDK and the
 * Vercel/Sentry integration tests — not duplicated here.
 */

describe("withDbSpan (KAR-532)", () => {
  it("returns the inner result on success", async () => {
    const result = await withDbSpan("select", "projects", async () => 42)
    expect(result).toBe(42)
  })

  it("re-throws the inner error", async () => {
    const boom = new Error("boom")
    await expect(
      withDbSpan("insert", "projects", async () => {
        throw boom
      }),
    ).rejects.toBe(boom)
  })

  it("supports every documented operation", async () => {
    const ops = ["select", "insert", "update", "delete", "rpc", "upsert"] as const
    for (const op of ops) {
      const result = await withDbSpan(op, "t", async () => op)
      expect(result).toBe(op)
    }
  })
})

describe("withBusinessSpan (KAR-532)", () => {
  it("returns the inner result and accepts attribute primitives", async () => {
    const result = await withBusinessSpan(
      "evaluation.created",
      { tenant_id: "t1", score: 7, ok: true },
      async () => "ok",
    )
    expect(result).toBe("ok")
  })

  it("re-throws inner errors", async () => {
    const boom = new Error("kaboom")
    await expect(
      withBusinessSpan("x", {}, async () => {
        throw boom
      }),
    ).rejects.toBe(boom)
  })
})

describe("recordBusinessMetric (KAR-532)", () => {
  it("exposes the pilot KPI registry and does not throw on use", () => {
    expect(() => recordBusinessMetric.evaluationCreated({ tenant_id: "t1" })).not.toThrow()
    expect(() => recordBusinessMetric.evaluationScore(7, { tenant_id: "t1" })).not.toThrow()
    expect(() => recordBusinessMetric.importDuration(123, { source: "supplier-csv" })).not.toThrow()
    expect(() => recordBusinessMetric.activeUsers(12)).not.toThrow()
  })
})
