import { getPackageInfo } from "@workshop/shared/packages"
import { test, expect } from "bun:test"
import { basename } from "node:path"
import { ensure } from "@workshop/shared/utils"

test("verify all package.json", async () => {
  const packageInfo = await getPackageInfo()
  const mainPackageFile = await Bun.file("package.json")
  const mainPackageJson = await mainPackageFile.json()
  const catalog = mainPackageJson.workspaces?.catalog ?? {}

  for (const { json, path } of packageInfo) {
    const dirname = basename(path)
    ensure(json, `package.json in ${dirname} must exist`)

    // Packages must be named after the dir they are in OR the name of the dir prefixed with @workshop/
    const unscopedName = json.name.replace("@workshop/", "")
    expect(unscopedName, `Name in package.json must match the dir name`).toBe(dirname)

    // Make sure all packages use the catalog version of deps
    const dependencies = { ...json.dependencies, ...json.devDependencies }
    Object.entries(dependencies).forEach(([dep, version]) => {
      if (!catalog[dep]) return
      expect(version, `Dependency "${dep}" in "${json.name}" must be "catalog:"`).toBe("catalog:") // The dep is in the catalog because having multiple versions causes hard to diagnose bugs
    })

    // If you define a subdomain:start you must also define subdomain:dev
    if (json.scripts?.["subdomain:start"]) {
      expect(json.scripts?.["subdomain:dev"], `subdomain:dev not defined in ${json.name}`).toBeDefined()
    }
  }
})
