import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { useSettingsStore } from '@/stores/settings'
import Login from '@/views/auth/Login.vue'
import Setup from '@/views/auth/Setup.vue'
import Register from '@/views/auth/Register.vue'
import Dashboard from '@/views/Dashboard.vue'
import Users from '@/views/Users.vue'
import Restaurants from '@/views/Restaurants.vue'
import OlapColumnsView from '@/views/OlapColumnsView.vue'
import DBConnections from '@/views/DBConnections.vue'
import AdminSettings from '@/views/AdminSettings.vue'
import Profile from '@/views/Profile.vue'
import NotFound from '@/views/NotFound.vue'

const routes = [
  {
    path: '/login',
    component: Login,
    meta: { title: 'Login', requiresAuth: false }
  },
  {
    path: '/register',
    component: Register,
    meta: { title: 'Register', requiresAuth: false }
  },
  {
    path: '/setup',
    component: Setup,
    meta: { title: 'Setup', requiresAuth: false }
  },
  {
    path: '/',
    redirect: '/dashboard'
  },
  {
    path: '/dashboard',
    component: Dashboard,
    meta: { requiresAuth: true, title: 'Dashboard' }
  },
  {
    path: '/users',
    component: Users,
    meta: { requiresAuth: true, requiresAdmin: true, title: 'Users' }
  },
  {
    path: '/restaurants',
    component: Restaurants,
    meta: { requiresAuth: true, title: 'Restaurants' }
  },
  {
    path: '/olap-columns',
    component: OlapColumnsView,
    meta: { requiresAuth: true, requiresAdmin: true, title: 'OlapColumns' }
  },
  {
    path: '/database-connections',
    component: DBConnections,
    meta: { requiresAuth: true, requiresAdmin: true, title: 'Database Connections' }
  },
  {
    path: '/settings',
    component: AdminSettings,
    meta: { requiresAuth: true, requiresAdmin: true, title: 'Settings' }
  },
  {
    path: '/profile',
    component: Profile,
    meta: { requiresAuth: true, title: 'Profile' }
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: NotFound,
    meta: { title: 'Page Not Found', requiresAuth: false }
  }
]

const router = createRouter({ history: createWebHistory(), routes })

router.beforeEach(async (to, from, next) => {
  const settings = useSettingsStore()
  if (!settings.siteName) await settings.loadSettings()

  document.title = to.meta.title ? `${to.meta.title} | ${settings.siteName}` : settings.siteName

  // Проверка необходимости установки (setup)
  try {
    const statusRes = await fetch('/api/status')
    const status = await statusRes.json()
    if (status.needsSetup && to.path !== '/setup') {
      next('/setup')
      return
    }
  } catch (e) { console.error('Failed to check status', e) }

  const userStore = useUserStore()
  // Если профиль ещё не загружен – загружаем
  if (userStore.role === '') {
    await userStore.fetchProfile()
  }

  // Если уже залогинены и пытаемся зайти на login/register – редирект на дашборд
  if (userStore.id && (to.path === '/login' || to.path === '/register')) {
    next('/dashboard')
    return
  }

  // Проверка доступности регистрации
  if (to.path === '/register' && !settings.enableRegistration) {
    next('/login')
    return
  }

  const requiresAuth = to.matched.some(record => record.meta.requiresAuth)
  const requiresAdmin = to.matched.some(record => record.meta.requiresAdmin)

  if (requiresAuth && !userStore.id) {
    next('/login')
  } else if (requiresAdmin && userStore.role !== 'admin') {
    next('/dashboard')
  } else {
    next()
  }
})

export default router
