import router from '@/router'

const ACCESS_TOKEN = 'BMAHRISCKI_KEYCLOAK_IDENTITY'
const key_C_Config = {
  url_Logout: import.meta.env.VITE_URL_SSO,
}

interface AuthResponse {
  access_token: string
  expires_in: number
  refresh_token: string
}

const authenticated = async () => ((await getToken()) ? true : false)

async function setAuthen(r: AuthResponse) {
  await setCookie(ACCESS_TOKEN, r.access_token, r.expires_in)
  await setCookieSso('y', r)
  window.location.href = '/'
}

async function setAuthenCheckin(r: AuthResponse) {
  await setCookieCheckin(ACCESS_TOKEN, r.access_token, r.expires_in)
  await setCookieSso('n', r)
  window.location.href = '/'
}

async function setCookieSso(val: string, r: AuthResponse) {
  setCookie('SSO', val, r.expires_in)
}

async function logout() {
  await deleteCookie(ACCESS_TOKEN)
  // window.location.href = key_C_Config.url_Logout
  router.push('/login')
}

async function getToken() {
  return getCookie(ACCESS_TOKEN)
}
// 2024-08-29T02:55:13.000Z
function setCookie(name: string, value: any, time: number) {
  let expires = ''
  if (time) {
    const date = new Date()
    date.setTime(date.getTime() + time * 1000)
    // date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
    date.setMonth(date.getMonth() + 6)
    expires = '; expires=' + date.toUTCString()
  }
  document.cookie = name + '=' + (value || '') + expires + '; path=/'
}

function setCookieCheckin(name: string, value: any, timeInSeconds: number) {
  let expires = ''
  if (timeInSeconds) {
    const date = new Date()
    // แปลงวินาทีเป็นมิลลิวินาที (คูณด้วย 1000)
    date.setTime(date.getTime() + timeInSeconds * 1000)
    expires = '; expires=' + date.toUTCString()
  }
  document.cookie = name + '=' + (value || '') + expires + '; path=/'
}

function getCookie(name: string) {
  const nameEQ = name + '='
  const ca = document.cookie.split(';')
  for (let i = 0; i < ca.length; i++) {
    let c = ca[i]
    while (c.charAt(0) == ' ') c = c.substring(1, c.length)
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length)
  }
  return null
}

function deleteCookie(name: string) {
  document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`
}

async function tokenParsed() {
  const token = await getCookie(ACCESS_TOKEN)
  if (!token) {
    return null
  }
  const base64Url = token.split('.')[1]
  const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/')
  const jsonPayload = decodeURIComponent(
    window
      .atob(base64)
      .split('')
      .map(function (c) {
        return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)
      })
      .join('')
  )

  return JSON.parse(jsonPayload)
}

export {
  getCookie,
  getToken,
  authenticated,
  logout,
  setAuthen,
  tokenParsed,
  setAuthenCheckin,
}
