import semver from "semver";
import { ERP_KIT_PACKAGE_NAME } from "../../../../util";
import {
  isNonSemverSpecifier,
  readDeclaredVersion,
  type VersionFinding,
  type WorkspacePackage,
} from "./shared";

export function checkErpKitVersion(
  packages: WorkspacePackage[],
  installedVersion: string,
): VersionFinding[] {
  const findings: VersionFinding[] = [];
  for (const pkg of packages) {
    const declared = readDeclaredVersion(pkg.manifest, ERP_KIT_PACKAGE_NAME);
    if (declared === undefined) continue;
    if (declared.startsWith("workspace:")) {
      findings.push({
        severity: "info",
        check: "erp-kit-version",
        subject: pkg.relativePath,
        message: `${ERP_KIT_PACKAGE_NAME}@${declared} uses the workspace protocol (expected only in the erp-kit dev repo).`,
      });
      continue;
    }
    if (isNonSemverSpecifier(declared)) {
      findings.push({
        severity: "warning",
        check: "erp-kit-version",
        subject: pkg.relativePath,
        message: `${ERP_KIT_PACKAGE_NAME}@${declared} uses a non-semver specifier; cannot compare against installed ${installedVersion}. Pin it to the exact installed version.`,
      });
      continue;
    }
    if (!semver.valid(declared)) {
      findings.push({
        severity: "error",
        check: "erp-kit-version",
        subject: pkg.relativePath,
        message: `${ERP_KIT_PACKAGE_NAME}@${declared} must be pinned to the exact installed version (${installedVersion}).`,
      });
      continue;
    }
    if (declared !== installedVersion) {
      findings.push({
        severity: "error",
        check: "erp-kit-version",
        subject: pkg.relativePath,
        message: `${ERP_KIT_PACKAGE_NAME}@${declared} differs from the installed version ${installedVersion}; pin it to match.`,
      });
    }
  }
  return findings;
}
