import { PUBLIC_URL } from '$env/static/public';

export async function checkExsistingUser(username, email) {
    const response = await fetch(`${PUBLIC_URL}/api/users/check_existing_user`, {
      method:'POST',
      credentials:"include",
      headers:{
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        "username": username,
        "email":    email
      })
    })
    if(response.status === 200){
      return ""
    }
    else if(response.status === 409){
      let data = "ЗАНЯТО НАХУЙ"
      return data
    }
    else if(response.status === 422){
      let data = await response.json();
      return "не похоже на почту"
    }
    else{
      console.log(response.status)
    }
}

export async function VerificationEmail(Code,token){
  const response = await fetch(`${PUBLIC_URL}/api/users/email_verification`,{
  method:'POST',
  credentials:'include',
  headers:{
    'Content-Type' : 'application/json',
    'Authorization': token 
  },
  body: JSON.stringify({
      "user_code": Code
    })
  })

  if(response.status === 200){
    window.location.href = '/'
    return true
  }
  else{
    return false
  }
}

export async function resendVerification(token){
  const response = await fetch(`${PUBLIC_URL}/api/users/resend_email_verification`,{
    method:'POST',
    credentials:'include',
    headers: {'Authorization': token }
  })

    if(response.ok){
      return "Отправлено"
    } else {
      console.log(response)
      return "Произошла ошибка"
    }
}

  export async function handleRegister(username,password,password2,email,date_of_birth){
    const response = await fetch(`${PUBLIC_URL}/api/users/register`,{
      method:'POST',
      credentials:"include",
      headers:{ 'Content-Type': 'application/json' },
      body: JSON.stringify({
        "email": email,
        "username": username,
        "password": password,
        "password2": password2,
        "date_of_birth": date_of_birth
      })
    })

    if(response.status === 201){
      const data = await response.json();
      const token = data.authorization
      localStorage.setItem('BPChat', token)
      return ""
    }
    else if(response.status === 422){
      console.log(response.status)
      let data = "Validation Error"
      return data
    }
    
  }