import { createRouter, createWebHistory } from 'vue-router';
import { useAuthStore } from '../store/auth';

// 视图组件导入 (确保所有引用的视图文件都存在于 src/views/ 目录下)
import HomeView from '../views/HomeView.vue';
import LoginView from '../views/LoginView.vue';
import RegisterView from '../views/RegisterView.vue';
import UserProfileView from '../views/UserProfileView.vue';
import GroupListView from '../views/GroupListView.vue';
import CreateGroupView from '../views/CreateGroupView.vue';
import GroupDetailView from '../views/GroupDetailView.vue';
import PostDetailView from '../views/PostDetailView.vue';
import UserListView from '../views/UserListView.vue'; // 如果你有这个独立的UserList页面
import RecommendationsView from '../views/RecommendationsView.vue';

// 占位组件
const PlaceholderView = { 
  template: '<div><h2 style="text-align:center; margin-top: 50px;">页面开发中...</h2><p style="text-align:center;"><router-link to="/">返回首页</router-link></p></div>' 
};


const routes = [
    { path: '/', name: 'Home', component: HomeView },
    { 
      path: '/login', name: 'Login', component: LoginView,
      beforeEnter: (to, from, next) => {
          const authStore = useAuthStore();
          if (authStore.isAuthenticated) next({ name: 'Home' });
          else next();
      } 
    },
    { 
      path: '/register', name: 'UserRegister', component: RegisterView,
      beforeEnter: (to, from, next) => {
          const authStore = useAuthStore();
          if (authStore.isAuthenticated) next({ name: 'Home' });
          else next();
      }
    },
    { path: '/profile', name: 'UserProfile', component: UserProfileView, meta: { requiresAuth: true } },
    { path: '/users/:id(\\d+)', name: 'UserProfileById', component: UserProfileView, props: true, meta: { requiresAuth: true } },
    { path: '/users', name: 'UserList', component: UserListView, meta: { requiresAuth: true } }, // 或 RecommendationsView
    { path: '/recommendations', name: 'Recommendations', component: RecommendationsView, meta: { requiresAuth: true } },
    { path: '/groups', name: 'GroupList', component: GroupListView, meta: { requiresAuth: true } },
    { path: '/groups/create', name: 'CreateGroup', component: CreateGroupView, meta: { requiresAuth: true } },
    { path: '/groups/:id(\\d+)', name: 'GroupDetail', component: GroupDetailView, props: true, meta: { requiresAuth: true } },
    { path: '/posts/:id(\\d+)', name: 'PostDetail', component: PostDetailView, meta: { requiresAuth: true }, props: true },
];

const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes,
    scrollBehavior: () => ({ top: 0 })
});

router.beforeEach(async (to, from, next) => {
    console.log(`Router: Navigating from ${from.name || 'start'} to ${to.name || to.path}`);
    const authStore = useAuthStore();

    // 确保Pinia store在路由守卫中可用
    // 如果accessToken存在但用户信息不存在，尝试自动登录（获取用户信息）
    // 这个操作应该在判断 requiresAuth 之前，以确保 isAuthenticated 状态准确
    if (authStore.accessToken && !authStore.currentUser && !authStore.isLoadingProfile) {
        console.log("Router Guard: Token exists, user missing. Attempting auto-login via fetchUserProfile.");
        await authStore.fetchUserProfile(); // 等待用户信息获取完毕
    }

    if (to.meta.requiresAuth && !authStore.isAuthenticated) {
        console.log(`Router Guard: Route ${String(to.name) || to.path} requires auth, user not authenticated. Redirecting to Login.`);
        next({ 
            name: 'Login', 
            query: { redirect: to.fullPath }
        });
    } else {
        console.log(`Router Guard: Navigation to ${String(to.name) || to.path} allowed.`);
        next();
    }
});

export default router;