// -----------------------------------------------------------------------------
// src/router/index.ts
// -----------------------------------------------------------------------------
import {
  createRouter,
  createWebHistory,
  createWebHashHistory,
  type RouteRecordRaw,
} from 'vue-router'

import HomePage from '@/components/HomePage.vue'
import AgentLibraryPage from '@/components/AgentLibraryPage.vue'
import ConversationPage from '@/components/ConversationPage.vue'
import NewAgent from '@/components/NewAgent.vue'
import DashboardPage from '@/components/DashboardPage.vue'
import SettingsPage from '@/components/SettingsPage.vue'
import AdminSettingsPage from '@/components/admin/AdminSettingsPage.vue'
import { API } from '@/Api'

// -----------------------------------------------------------------------------
// 1. Route table
// -----------------------------------------------------------------------------
const routes: RouteRecordRaw[] = [
  { path: '/', name: 'Home', component: HomePage },
  { path: '/agents', name: 'AgentLibrary', component: AgentLibraryPage },
  {
    path: '/conversations',
    name: 'Conversations',
    component: ConversationPage,
    props: (route) => ({
      submit: route.query.submit === 'true' || false,
    }),
  },
  { path: '/agents/new', name: 'NewAgent', component: NewAgent },
  { path: '/agents/:id/edit', name: 'EditAgent', component: NewAgent },
  { path: '/dashboard', name: 'Dashboard', component: DashboardPage },
  { path: '/settings', name: 'Settings', component: SettingsPage },
  {
    path: '/settings/admin',
    name: 'AdminSettings',
    component: AdminSettingsPage,
    // Only project admins can access this page
    async beforeEnter() {
      try {
        const { data } = await API.getCurrentUser()
        return data?.hasWriteAccess ? true : { name: 'Settings' }
      } catch {
        return { name: 'Settings' }
      }
    },
  },
]

// -----------------------------------------------------------------------------
// 2. Detect <base href="…"> that DSS injects
// -----------------------------------------------------------------------------
function inIframe(): boolean {
  try {
    return window.self !== window.top
  } catch (e) {
    return true
  }
}

function getBase(): string {
  if (inIframe()) {
    const pathName = window.location.pathname

    if (pathName.includes('/dip/')) {
      // in iframe in dataiku
      return '/dip/api/webapps/view'
    } else {
      // in iframe not in dataiku
      // Ensure it ends with a slash for Vue Router
      const base = pathName.endsWith('/') ? pathName : `${pathName}/`
      return base
    }
  } else {
    // outside iframe
    let location = window.location.pathname.match(
      /(\/public-webapps\/[a-zA-Z0-9\-_]*\/[a-zA-Z0-9\-_]*).*/
    )

    if (location) {
      // as public-webapp
      return `${location[1]}/`
    } else {
      // check as webapp
      location = window.location.pathname.match(/(\/webapps\/[a-zA-Z0-9\-_]*\/[a-zA-Z0-9\-_]*).*/)
    }

    // either webapp or no path
    // Ensure it ends with a slash for Vue Router
    return location ? `${location[1]}/` : '/'
  }
}

function pickHistory() {
  const base = getBase()
  return window.location.pathname.startsWith(base)
    ? createWebHistory(base)
    : createWebHashHistory(base) // fallback for DSS iframe
}

// -----------------------------------------------------------------------------
// 4. Create & export the router
// -----------------------------------------------------------------------------
export default createRouter({
  history: pickHistory(),
  routes,
  scrollBehavior() {
    // always scroll to top on navigation change
    return { top: 0 }
  },
})
