import { createRouter, createWebHistory } from 'vue-router'
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 AdminSettings from '../views/AdminSettings.vue'
import NotFound from '../views/NotFound.vue'

const routes = [
  { path: '/login', component: Login, meta: { title: 'Login' } },
  { path: '/register', component: Register, meta: { title: 'Register' } },
  { path: '/setup', component: Setup, meta: { title: 'Setup' } },
  {
    path: '/',
    redirect: '/dashboard'
  },
  {
    path: '/dashboard',
    component: Dashboard,
    meta: { requiresAuth: true, title: 'Dashboard' }
  },
  {
    path: '/users',
    component: Users,
    meta: { requiresAuth: true, title: 'Users' }
  },
  {
    path: '/restaurants',
    component: Restaurants,
    meta: { requiresAuth: true, title: 'Restaurants' }
  },
  {
    path: '/settings',
    component: AdminSettings,
    meta: { requiresAuth: true, title: 'Settings' }
  },
  {
     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) => {
  // Update page title
  document.title = `${to.meta.title || 'Admin Panel'} | AdminPanel`

  // Check if setup is needed
  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)
  }

  if (to.path === '/login') {
    try {
      const meRes = await fetch('/api/admin/me');
      if (meRes.ok) {
        next('/dashboard');
        return;
      }
    } catch (e) {
      // игнорируем ошибку, продолжаем
    }
  }

  // Check authentication
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth)

  if (requiresAuth) {
    try {
      const res = await fetch('/api/admin/me')
      if (!res.ok) {
        next('/login')
      } else {
        next()
      }
    } catch {
      next('/login')
    }
  } else {
    next()
  }
})

export default router
