import liff from '@line/liff'
import Cookie from 'js-cookie'

import { lineLogin } from '@/services/auth'

async function checkLogin(to,from,next){

    const code = to.query.code

    await liff.init({ liffId: '1657782615-qGK9WQ5m' });

    if(code){
  
        if (!liff.isLoggedIn())
            liff.login({ redirectUri: window.location.href });
    
        let res = await lineLogin({token:liff.getIDToken()})
    
    
        switch(res.code){
          case 200:
            Cookies.set('token',res.data.token,{ expires: 30 ,domain: import.meta.env.VITE_APP_SSO_DOMAIN})
            return next('/user')
            break
          case 201:
            return next('/linereg')
            break
          case 401:
            return next('/login')
            break
          default:
            return next('/login')
            break
        }        
    }else{
        liff.logout()
    }
    
    return next()
}

export default checkLogin