import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
import Texts from '../views/Texts.vue'
import TextReader from '../views/TextReader.vue'
import { textService } from '../services/textService.js'

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/textes',
    name: 'Texts',
    component: Texts
  },
  {
    path: '/texte/:id',
    name: 'TextReader',
    component: TextReader,
    props: true
  },
  {
    path: '/au-hasard',
    name: 'Random',
    beforeEnter: async (to, from, next) => {
      try {
        const randomText = await textService.getRandomText()
        next(`/texte/${randomText.id}`)
      } catch (error) {
        console.error('Erreur lors de la redirection vers un texte aléatoire:', error)
        next('/textes')
      }
    }
  }
]

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

export default router
