/**
 * Registry utilities shared by registry management surfaces.
 */

export interface RegistryRule {
  repository: string
  actions: string[]
}

export const REGISTRY_SEGMENT_REGEX = /^[a-z0-9]+(?:[._-][a-z0-9]+)*$/
export const REGISTRY_ACTION_ORDER = ['pull', 'push', 'delete']

export function isValidRegistryPattern(value: string): boolean {
  if (!value || value.length > 255) {
    return false
  }
  if (value === '*') {
    return true
  }
  const segments = value.split('/')
  return segments.every(segment => segment === '*' || REGISTRY_SEGMENT_REGEX.test(segment))
}

export function sortRegistryActions(values: string[]): string[] {
  const ordered = REGISTRY_ACTION_ORDER.filter(action => values.includes(action))
  const extras = values.filter(value => !REGISTRY_ACTION_ORDER.includes(value))
  return [...ordered, ...extras]
}

export function getCheckedValues(inputs: NodeListOf<HTMLInputElement>): string[] {
  return Array.from(inputs)
    .filter(input => input.checked)
    .map(input => input.value)
}

export function errorMessage(error: unknown): string {
  if (error instanceof Error) {
    return error.message
  }
  return 'Unknown error'
}
