import type {
  ComponentUseOption,
  LegacyPhoneUsePolicyOption,
  PhoneUsePolicyOption,
  ServiceUseOption,
} from '../model/types'

type PhonePolicyValue =
  | PhoneUsePolicyOption
  | LegacyPhoneUsePolicyOption
  | boolean
  | null
  | undefined

export function isPhonePolicyOptionEnabled(value: PhonePolicyValue) {
  if (typeof value === 'boolean') return value

  return value === 'Enabled' || value === 'Allowed'
}

export function booleanToPhonePolicyOption(
  enabled: boolean,
): ServiceUseOption {
  return enabled ? 'Enabled' : 'Disabled'
}

export function booleanToServiceUseOption(enabled: boolean): ServiceUseOption {
  return enabled ? 'Enabled' : 'Disabled'
}

export function booleanToComponentUseOption(
  enabled: boolean,
): ComponentUseOption {
  return enabled ? 'Allowed' : 'Disallowed'
}

export function normalizeServiceUseOption(
  value?: ServiceUseOption | LegacyPhoneUsePolicyOption | boolean | null,
  fallbackBoolean?: boolean | null,
): ServiceUseOption {
  if (value === 'Disabled' || value === 'Enabled' || value === 'Unspecified') {
    return value
  }

  if (value === 'Allowed') return 'Enabled'
  if (value === 'Disallowed') return 'Disabled'
  if (value === 'Changeable') return 'Unspecified'

  if (typeof value === 'boolean') {
    return booleanToServiceUseOption(value)
  }

  if (typeof fallbackBoolean === 'boolean') {
    return booleanToServiceUseOption(fallbackBoolean)
  }

  return 'Unspecified'
}

export function normalizeComponentUseOption(
  value?:
    | ComponentUseOption
    | ServiceUseOption
    | LegacyPhoneUsePolicyOption
    | boolean
    | null,
  fallbackBoolean?: boolean | null,
): ComponentUseOption {
  if (value === 'Allowed' || value === 'Disallowed') {
    return value
  }

  if (value === 'Enabled') return 'Allowed'
  if (value === 'Disabled') return 'Disallowed'

  if (typeof value === 'boolean') {
    return booleanToComponentUseOption(value)
  }

  if (typeof fallbackBoolean === 'boolean') {
    return booleanToComponentUseOption(fallbackBoolean)
  }

  return 'Disallowed'
}
