import { describe, it, expect } from "vitest";
import { RecordingTracer, RecordingLogger } from "@repo/core-testing/instrumentation";
import { MockUsersRepository } from "@/infrastructure/repositories/users.repository.mock";

// Mock repo also wraps in spans (R42); easier to assert without booting Payload.
describe("MockUsersRepository emits spans (R42)", () => {
  it("getUser emits one span with op='repository'", async () => {
    const tracer = new RecordingTracer();
    const logger = new RecordingLogger();
    const repo = new MockUsersRepository([], tracer, logger);
    await repo.getUser("missing");
    expect(tracer.spans).toHaveLength(1);
    expect(tracer.spans[0]).toMatchObject({
      name: "users.getUser",
      op: "repository",
    });
    expect(tracer.spans[0]!.attributes.id).toBe("missing");
    expect(tracer.spans[0]!.attributes.found).toBe(false);
  });

  it("getUserByUsername emits a span with emailDomain attribute", async () => {
    const tracer = new RecordingTracer();
    const repo = new MockUsersRepository(
      [{ id: "1", username: "alice", passwordHash: "hash" }],
      tracer,
    );
    await repo.getUserByUsername("alice");
    expect(tracer.findSpan("users.getUserByUsername")).toBeDefined();
    expect(tracer.findSpan("users.getUserByUsername")!.attributes.found).toBe(true);
  });

  it("createUser records created=true", async () => {
    const tracer = new RecordingTracer();
    const repo = new MockUsersRepository([], tracer);
    await repo.createUser({ id: "u1", username: "charlie", passwordHash: "hash" });
    expect(tracer.findSpan("users.createUser")).toBeDefined();
    expect(tracer.findSpan("users.createUser")!.attributes.created).toBe(true);
  });
});
