import { describe, expect, it, jest } from "@jest/globals"

jest.doMock("@/env/server", () => ({
  env: {
    NODE_ENV: "test",
  },
}))

const { env } = require("@/env/server")
const { getPrefix } = require("./getPrefix")

const mockedEnv = env as { BRANCH: string; GIT_SHA: string }

describe("getPrefix", () => {
  const OLD_ENV = process.env

  beforeEach(() => {
    jest.resetModules()
  })

  afterEach(() => {
    process.env = OLD_ENV
  })

  it.each([
    "prod",
    "production",
    "release",
    "release-v1",
    "release-v2",
    "release-v2-alpha",
    "release-v2.1-alpha",
    "release-v2.1.2-alpha",
  ])(
    "should return gitsha for production branches when name is '%s'",
    (branchName: string) => {
      mockedEnv.BRANCH = branchName
      mockedEnv.GIT_SHA = "gitsha"

      const result = getPrefix()

      expect(result).toBe("gitsha")
    }
  )

  it.each([
    "fix/stuff",
    "feat/my-feature",
    "feature/my-feature",
    "releasee",
    "release-vA",
    "FEAT",
  ])(
    "should return branch name and gitsha for non-production branches when name is '%s'",
    (branchName: string) => {
      mockedEnv.BRANCH = branchName
      mockedEnv.GIT_SHA = "gitsha"

      const result = getPrefix()

      expect(result).toBe(`${mockedEnv.BRANCH}:${mockedEnv.GIT_SHA}`)
    }
  )

  it("should throw if BRANCH and/or GIT_SHA is not set", () => {
    mockedEnv.BRANCH = ""
    mockedEnv.GIT_SHA = ""

    expect(getPrefix).toThrow(
      "Unable to getPrefix, BRANCH and GIT_SHA must be set"
    )

    mockedEnv.BRANCH = "hasBranch"
    mockedEnv.GIT_SHA = ""

    expect(getPrefix).toThrow("Unable to getPrefix, GIT_SHA must be set")

    mockedEnv.BRANCH = ""
    mockedEnv.GIT_SHA = "hasGitSha"

    expect(getPrefix).toThrow("Unable to getPrefix, BRANCH must be set")
  })

  it("should return dev or local user if running locally", () => {
    ;(process.env.NODE_ENV as any) = "development"

    process.env.USER = "test_user"
    process.env.USERNAME = "test_username"

    mockedEnv.BRANCH = ""
    mockedEnv.GIT_SHA = ""

    expect(getPrefix()).toBe("test_user")

    process.env.USER = ""

    expect(getPrefix()).toBe("test_username")

    process.env.USERNAME = ""
    expect(getPrefix()).toBe("dev")
  })
})
