import { getCredentialSchema } from './schemas'

/**
 * Build credential value object from form values
 *
 * Constructs the credential value object based on the schema's field definitions:
 * - Single field: { apiKey: "..." }
 * - Multi field: { apiKey: "...", token: "..." }
 * - OAuth: Not used (OAuth flow handles this)
 *
 * @param type - Credential type identifier
 * @param formValues - Form field values (key-value pairs)
 * @returns Credential value object ready for API submission
 */
export function buildCredentialValue(type: string, formValues: Record<string, string>): Record<string, unknown> {
  const schema = getCredentialSchema(type)

  // OAuth types shouldn't use this function (handled via OAuth flow)
  if (schema.type === 'oauth') {
    throw new Error(`buildCredentialValue should not be used for OAuth type: ${type}`)
  }

  // Build value object from schema fields
  const value: Record<string, unknown> = {}

  if (schema.fields) {
    for (const field of schema.fields) {
      const fieldValue = formValues[field.key]
      if (fieldValue !== undefined && fieldValue !== null) {
        value[field.key] = fieldValue.trim()
      }
    }
  }

  return value
}

/**
 * Extract form field values from credential value object
 *
 * Inverse of buildCredentialValue - used in Edit modal to populate form fields
 *
 * @param credentialValue - Credential value object from database
 * @returns Form field values (key-value pairs)
 */
export function extractFormValues(credentialValue: Record<string, unknown>): Record<string, string> {
  const formValues: Record<string, string> = {}

  for (const [key, value] of Object.entries(credentialValue)) {
    if (typeof value === 'string') {
      formValues[key] = value
    } else if (value !== null && value !== undefined) {
      // Convert non-string values to strings for form inputs
      formValues[key] = String(value)
    }
  }

  return formValues
}
