// 服务端 Mock 初始化
let isServerMockEnabled = false

export async function initServerMock() {
  // 避免重复初始化
  if (isServerMockEnabled) {
    return
  }

  // 只在开发环境启用
  if (process.env.NODE_ENV !== 'development') {
    return
  }

  // 检查是否启用 mock
  const shouldMock = process.env.NEXT_PUBLIC_ENABLE_MOCK === 'true'
  if (!shouldMock) {
    return
  }

  try {
    // 动态导入服务端 MSW
    const { server } = await import('../mocks/server')

    // 启动服务端 mock
    server.listen({
      onUnhandledRequest: 'bypass',
    })

    isServerMockEnabled = true
    console.log('🎭 MSW Server started successfully')
  } catch (error) {
    console.error('❌ Failed to start MSW Server:', error)
  }
}

// 在服务端自动初始化
if (typeof window === 'undefined') {
  initServerMock()
}
