import { Language, translate } from '@stack-spot/portal-translate'
import { GeneratedConnectionsManager } from './ConnectionInterface'
import { errorDictionary } from './error-dictionary'
import { ContextInput } from './types'

const regex = /^[\w-]+$/

export async function validateGeneratedConnection(
  value: string,
  input: ContextInput,
  language: Language,
  formName: string,
  isConnectionInterfaceNameAvailable: (value: string) => Promise<boolean>,
  generatedConnectionsManager: GeneratedConnectionsManager,
) {
  if (input.type !== 'generated-connection' || !input.connectionInterfaceType) return
  const key = `${formName}.${input.name}`
  if (!regex.test(value)) return translate(errorDictionary, language).invalidConnectionNamePattern
  let isValid = true
  if (generatedConnectionsManager.getByType(input.connectionInterfaceType).includes(value)) {
    isValid = false
  } else {
    isValid = await isConnectionInterfaceNameAvailable(value)
  }
  if (isValid) {
    generatedConnectionsManager.set(key, input.connectionInterfaceType, value)
  } else {
    generatedConnectionsManager.unset(key)
    return translate(errorDictionary, language).alreadyInUse
  }
}
