import { isValidCPF } from '@brazilian-utils/brazilian-utils'
import {
  adjectives,
  colors,
  NumberDictionary,
  uniqueNamesGenerator
} from 'unique-names-generator'
import { z } from 'zod'

const isName = (name: string) => name && name.includes(' ')

function randomEmail() {
  const numberDict = NumberDictionary.generate({ min: 100, max: 999 })
  const randomName: string = uniqueNamesGenerator({
    dictionaries: [adjectives, colors, numberDict],
    length: 3,
    separator: '-'
  })

  return `${randomName}@users.noreply.saladeaula.digital`
}

export const formSchema = z
  .object({
    name: z
      .string()
      .trim()
      .nonempty('Digite um nome')
      .refine(isName, { message: 'Nome inválido' }),
    email: z.string().trim().toLowerCase().optional(),
    cpf: z
      .string('CPF obrigatório')
      .refine(isValidCPF, { message: 'CPF inválido' }),
    given_email: z.coerce.boolean()
  })
  .refine(
    ({ given_email, email }) => {
      if (given_email) {
        return true
      }
      return email && z.email().safeParse(email).success
    },
    {
      message: 'Email inválido',
      path: ['email']
    }
  )
  .transform((data) => {
    if (data.given_email) {
      return { ...data, email: randomEmail() }
    }
    return data
  })

export type Schema = z.infer<typeof formSchema>
