import { zuiKey } from '../../../z'
import { JsonSchemaObject } from '../types'
import { withMessage } from '../utils'

export const parseNumber = (schema: JsonSchemaObject & { type: 'number' | 'integer' }) => {
  let r = 'z.number()'

  if (schema[zuiKey]?.coerce) {
    r = 'z.coerce.number()'
  }

  if (schema.type === 'integer') {
    r += withMessage(schema, 'type', () => ['.int(', ')'])
  } else {
    r += withMessage(schema, 'format', ({ value }) => {
      if (value === 'int64') {
        return ['.int(', ')']
      }
    })
  }

  r += withMessage(schema, 'multipleOf', ({ value, json }) => {
    if (value === 1) {
      if (r.startsWith('z.number().int(')) {
        return
      }

      return ['.int(', ')']
    }

    return [`.multipleOf(${json}`, ', ', ')']
  })

  if (typeof schema.minimum === 'number') {
    if (schema.exclusiveMinimum === true) {
      r += withMessage(schema, 'minimum', ({ json }) => [`.gt(${json}`, ', ', ')'])
    } else {
      r += withMessage(schema, 'minimum', ({ json }) => [`.gte(${json}`, ', ', ')'])
    }
  } else if (typeof schema.exclusiveMinimum === 'number') {
    r += withMessage(schema, 'exclusiveMinimum', ({ json }) => [`.gt(${json}`, ', ', ')'])
  }

  if (typeof schema.maximum === 'number') {
    if (schema.exclusiveMaximum === true) {
      r += withMessage(schema, 'maximum', ({ json }) => [`.lt(${json}`, ', ', ')'])
    } else {
      r += withMessage(schema, 'maximum', ({ json }) => [`.lte(${json}`, ', ', ')'])
    }
  } else if (typeof schema.exclusiveMaximum === 'number') {
    r += withMessage(schema, 'exclusiveMaximum', ({ json }) => [`.lt(${json}`, ', ', ')'])
  }

  return r
}
