import { createRouter, createWebHistory, type RouteRecordRaw } from 'vue-router'
import { useAuthStore } from '@/stores/auth.store'

// 코드 스플리팅 — 모든 페이지 컴포넌트는 lazy import 처리
const routes: RouteRecordRaw[] = [
  {
    path: '/',
    redirect: '/projects',
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/pages/relay/LoginPage.vue'),
    meta: { requiresAuth: false },
  },
  {
    path: '/signup',
    name: 'signup',
    component: () => import('@/pages/relay/SignupPage.vue'),
    meta: { requiresAuth: false },
  },
  {
    path: '/forgot-password',
    name: 'forgot-password',
    component: () => import('@/pages/relay/ForgotPasswordPage.vue'),
    meta: { requiresAuth: false },
  },
  {
    path: '/reset-password',
    name: 'reset-password',
    component: () => import('@/pages/relay/ResetPasswordPage.vue'),
    meta: { requiresAuth: false },
  },
  {
    // 이메일 인증 결과(메일 링크의 도착지) — 완료 표시 후 창 닫기
    path: '/email-verified',
    name: 'email-verified',
    component: () => import('@/pages/relay/EmailVerifiedPage.vue'),
    meta: { requiresAuth: false },
  },
  {
    path: '/projects',
    name: 'project-list',
    component: () => import('@/pages/relay/ProjectListPage.vue'),
    meta: { requiresAuth: true },
  },
  {
    // 정적 '/projects/new' 는 동적 '/projects/:projectId' 보다 먼저 선언
    path: '/projects/new',
    name: 'project-create',
    component: () => import('@/pages/relay/ProjectCreatePage.vue'),
    meta: { requiresAuth: true },
  },
  {
    path: '/projects/:projectId',
    name: 'project-detail',
    component: () => import('@/pages/relay/ProjectDetailPage.vue'),
    meta: { requiresAuth: true },
  },
  {
    path: '/projects/:projectId/members',
    name: 'project-members',
    component: () => import('@/pages/relay/ProjectMembersPage.vue'),
    meta: { requiresAuth: true },
  },
  {
    path: '/projects/:projectId/activity',
    name: 'project-activity',
    component: () => import('@/pages/relay/ProjectActivityPage.vue'),
    meta: { requiresAuth: true },
  },
  {
    path: '/projects/:projectId/settings',
    name: 'project-settings',
    component: () => import('@/pages/relay/ProjectSettingsPage.vue'),
    meta: { requiresAuth: true },
  },
  {
    path: '/projects/:projectId/tasks/new',
    name: 'task-create',
    component: () => import('@/pages/relay/TaskCreatePage.vue'),
    meta: { requiresAuth: true },
  },
  {
    // 업무 수정 — 생성 폼(TaskCreatePage)을 편집 모드로 재사용
    path: '/projects/:projectId/tasks/:taskId/edit',
    name: 'task-edit',
    component: () => import('@/pages/relay/TaskCreatePage.vue'),
    meta: { requiresAuth: true },
  },
  {
    path: '/projects/:projectId/tasks/:taskId',
    name: 'task-detail',
    component: () => import('@/pages/relay/TaskDetailPage.vue'),
    meta: { requiresAuth: true },
  },
  {
    // '내 업무' — 담당/지시 프로젝트 횡단 집계
    path: '/tasks',
    name: 'my-tasks',
    component: () => import('@/pages/relay/MyTasksPage.vue'),
    meta: { requiresAuth: true },
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'not-found',
    component: () => import('@/pages/NotFoundPage.vue'),
  },
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
})

// 네비게이션 가드 — 세션 부트스트랩 + 인증 분기
router.beforeEach(async (to) => {
  const authStore = useAuthStore()

  // 앱 최초 진입 시 1회 세션 복원(/auth/me). 이후는 캐시된 상태 사용
  if (!authStore.bootstrapped) {
    await authStore.bootstrap()
  }

  // 보호 라우트인데 미로그인 → 로그인 페이지로 (로그인 후에는 항상 프로젝트 목록으로 진입)
  if (to.meta.requiresAuth && !authStore.isLoggedIn) {
    return { name: 'login' }
  }

  // 이미 로그인 상태에서 로그인/회원가입 진입 → 프로젝트 목록으로
  if (
    !to.meta.requiresAuth &&
    authStore.isLoggedIn &&
    (to.name === 'login' || to.name === 'signup')
  ) {
    return { path: '/projects' }
  }

  return true
})

export default router
