import pako from 'pako'
import { useCookies } from 'vue3-cookies'
const { cookies } = useCookies()

function getAuthRoute(authRoute: string, nextRoute: string): string {
  const next = `${location.protocol}//${location.host}${nextRoute}`
  return `${
    import.meta.env.VITE_API_URL
  }api/${authRoute}?next_url=${encodeURIComponent(`${next}`)}`
}

// This function to decode the flask cookie and have the user information like username
function decodingFlaskCookie(cookie: string): string {
  const cookieFormatted = cookie
    .split('.')[1]
    .replace(/_/g, '/')
    .replace(/-/g, '+')
  const binaryString = atob(cookieFormatted)
  const bytes = new Uint8Array(binaryString.length)
  for (let i = 0; i < binaryString.length; i++) {
    bytes[i] = binaryString.charCodeAt(i)
  }
  return pako.inflate(bytes.buffer, { to: 'string' })
}

function hasASessionCookieDecoded(): { account: { name: string } } | null {
  if (cookies.get('session')) {
    return JSON.parse(decodingFlaskCookie(cookies.get('session')))
  }
  return null
}

export { getAuthRoute, hasASessionCookieDecoded, decodingFlaskCookie }
