import { describe, expect, test } from "bun:test"

import { checkUsername, isUsername, normaliseUsername } from "@/lib/username"

describe("normaliseUsername", () => {
  /** Caps lock on a factory terminal should not keep somebody out. */
  test("folds case and trims", () => {
    expect(normaliseUsername("  N.Kulisra ")).toBe("n.kulisra")
  })
})

describe("checkUsername", () => {
  test("accepts what HR would reasonably choose", () => {
    for (const name of [
      "roma",
      "n.kulisra",
      "malai_k",
      "line-leader-1",
      "a1b",
    ]) {
      expect(isUsername(name)).toBe(true)
    }
  })

  test("refuses what would cause trouble later", () => {
    expect(checkUsername("ab")).toBe("too_short")
    expect(checkUsername("a".repeat(33))).toBe("too_long")
    expect(checkUsername("has space")).toBe("bad_characters")
    expect(checkUsername("มาลัย")).toBe("bad_characters")
    expect(checkUsername("a@b")).toBe("bad_characters")
  })

  /**
   * A leading or trailing dot survives a copy and paste and then nobody can
   * find the account they are looking for.
   */
  test("refuses an edge that hides itself", () => {
    expect(checkUsername(".roma")).toBe("bad_characters")
    expect(checkUsername("roma.")).toBe("bad_characters")
  })

  test("case is not a difference", () => {
    expect(isUsername("ROMA")).toBe(true)
    expect(normaliseUsername("ROMA")).toBe(normaliseUsername("roma"))
  })
})
