/**
 * @vitest-environment jsdom
 */
import { cleanup, render, screen } from "@testing-library/react";
import { afterEach, describe, expect, it } from "vitest";
import { getUserIdentifierParts, UserIdentifier } from "./user-identifier";

afterEach(() => {
  cleanup();
});

type DeviceWithOptionalNo = API.UserDevice & { device_no?: string };

describe("getUserIdentifierParts", () => {
  it("uses the device number and D label for device-auth users", () => {
    expect(
      getUserIdentifierParts({
        auth_methods: [
          {
            auth_type: "device",
            auth_identifier: "raw-device-id",
            verified: true,
          },
        ],
        user_devices: [
          {
            id: 1,
            ip: "127.0.0.1",
            identifier: "device-id",
            user_agent:
              "Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X)",
            online: true,
            enabled: true,
            created_at: 0,
            updated_at: 0,
            device_no: "DVC-001",
          } satisfies DeviceWithOptionalNo,
        ],
      })
    ).toMatchObject({
      authLabel: "(D)",
      identifier: "DVC-001",
      isDevice: true,
    });
  });

  it("falls back to the raw identifier and E label for email-auth users", () => {
    expect(
      getUserIdentifierParts({
        auth_methods: [
          {
            auth_type: "email",
            auth_identifier: "user@example.com",
            verified: true,
          },
        ],
        user_devices: [],
      })
    ).toMatchObject({
      authLabel: "(E)",
      identifier: "user@example.com",
      isDevice: false,
    });
  });
});

describe("UserIdentifier", () => {
  it("renders the compact auth label and visible identifier", () => {
    render(
      <UserIdentifier
        user={{
          auth_methods: [
            {
              auth_type: "email",
              auth_identifier: "referrer@example.com",
              verified: true,
            },
          ],
          user_devices: [],
        }}
      />
    );

    expect(screen.getByText("(E)")).not.toBeNull();
    expect(screen.getByText("referrer@example.com")).not.toBeNull();
  });

  it("renders an empty fallback when no identifier is available", () => {
    render(
      <UserIdentifier
        user={{
          auth_methods: [],
          user_devices: [],
        }}
      />
    );

    expect(screen.getByText("(E)")).not.toBeNull();
    expect(screen.getByText("--")).not.toBeNull();
  });
});
