import { z } from 'zod'
import { isValidCPF } from '@brazilian-utils/brazilian-utils'
import { createContext } from 'react'

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

export type User = {
  id?: string | null
  cpf: string
  name: string
  email: string
  never_logged?: boolean
}

export const cpf = z
  .string()
  .nonempty('Digite seu CPF')
  .refine(isValidCPF, 'Deve ser um CPF válido')

export const formSchema = z
  .object({
    name: z
      .string()
      .trim()
      .nonempty('Digite seu nome')
      .refine(isName, { message: 'Nome inválido' }),
    email: z.email('Digite seu email'),
    password: z
      .string()
      .nonempty('Digite sua senha')
      .min(6, 'Deve ter no mínimo 6 caracteres'),
    confirm_password: z.string(),
    cpf: cpf
  })
  .refine((data) => data.password === data.confirm_password, {
    message: 'As senhas não coincidem',
    path: ['confirm_password']
  })

export type Schema = z.infer<typeof formSchema>

export type RegisterContextProps = {
  user: User | null
  setUser: (user: User) => void
}
export const RegisterContext = createContext<RegisterContextProps | null>(null)
