import { createRouter, createWebHistory } from 'vue-router'
import type {
  RouteRecordRaw,
  NavigationGuardNext,
  RouteLocationNormalized
} from 'vue-router'
import axios from 'axios'
import { getAuthRoute, hasASessionCookieDecoded } from '@/utils/auth'
import HomeView from '../views/HomeView.vue'
import MyInformationView from '../views/MyInformationView.vue'
import MySettingsView from '../views/MySettingsView.vue'
import MySequencesView from '../views/MySequencesView.vue'
import MySequenceView from '../views/MySequenceView.vue'
import SharePicturesView from '../views/SharePicturesView.vue'
import UploadPicturesView from '../views/UploadPicturesView.vue'
import Ay11View from '../views/Ay11View.vue'
let routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'home',
    component: HomeView
  },
  {
    path: '/mes-informations',
    name: 'my-information',
    component: MyInformationView
  },
  {
    path: '/mes-parametres',
    name: 'my-settings',
    component: MySettingsView
  },
  {
    path: '/mes-sequences',
    name: 'my-sequences',
    component: MySequencesView
  },
  { path: '/sequence/:id', name: 'sequence', component: MySequenceView },
  {
    path: '/pourquoi-contribuer',
    name: 'why-contribute',
    component: SharePicturesView
  },
  {
    path: '/envoyer',
    name: 'upload-pictures',
    component: UploadPicturesView
  }
]

if (window.location.href.includes('.ign.')) {
  routes = [
    ...routes,
    {
      path: '/accessibilite',
      name: 'ay11',
      component: Ay11View
    }
  ]
}

const router = createRouter({
  history: createWebHistory(),
  routes
})
router.beforeResolve(
  async (
    to: RouteLocationNormalized,
    from: RouteLocationNormalized,
    next: NavigationGuardNext
  ) => {
    const siteLoggedRoutes =
      to.name === 'my-settings' ||
      to.name === 'my-sequences' ||
      to.name === 'upload-pictures'

    if (siteLoggedRoutes) {
      if (!isSiteLogged()) {
        goToLoginPage(to.path)
      } else return next()
    }
    if (to.name === 'my-information') {
      try {
        const keycloakLogout = await isKeycloakLogout()
        if (keycloakLogout.status >= 300 || !isSiteLogged()) {
          return goToLoginPage(to.path)
        } else return next()
      } catch (e) {
        return goToLoginPage(to.path)
      }
    }
    next()
  }
)

function isSiteLogged(): boolean {
  const cookie = hasASessionCookieDecoded()
  return !!(cookie && cookie.account)
}

async function isKeycloakLogout(): Promise<{ status: number }> {
  const loginUrl = `/api/users/me`
  return await axios.get(loginUrl)
}

function goToLoginPage(path: string): void {
  window.location.replace(getAuthRoute('auth/login', path))
}

export default router
