/**
 * 临时测试API - 验证平台基础设施
 * 
 * 使用方法：
 * 1. 在 index.ts 中注册这个路由
 * 2. 访问 http://localhost:3001/test/platform
 */

import { FastifyInstance } from 'fastify'
import { storage } from './common/storage/index.js'
import { logger } from './common/logging/index.js'
import { cache } from './common/cache/index.js'
import { jobQueue } from './common/jobs/index.js'

export async function registerTestRoutes(app: FastifyInstance) {
  app.get('/test/platform', async (_request, reply) => {
    const results: any = {
      timestamp: new Date().toISOString(),
      tests: {}
    }

    // 测试 1: 存储服务
    try {
      const testKey = 'test/verification-' + Date.now() + '.txt'
      const testContent = Buffer.from('平台基础设施验证 - ' + new Date().toISOString(), 'utf-8')
      
      const url = await storage.upload(testKey, testContent)
      const downloaded = await storage.download(testKey)
      const exists = await storage.exists(testKey)
      await storage.delete(testKey)
      
      results.tests.storage = {
        status: 'passed',
        upload: url,
        downloadSize: downloaded.length,
        contentMatch: downloaded.toString('utf-8') === testContent.toString('utf-8'),
        exists: exists
      }
      
      logger.info('存储服务测试通过', { key: testKey })
    } catch (error) {
      results.tests.storage = {
        status: 'failed',
        error: (error as Error).message
      }
      logger.error('存储服务测试失败', { error: (error as Error).message })
    }

    // 测试 2: 日志系统
    try {
      logger.info('日志系统测试：Info级别', { test: 'platform-verification' })
      logger.warn('日志系统测试：Warn级别', { test: 'platform-verification' })
      
      const contextLogger = logger.child({ module: 'Test', testId: 'verification' })
      contextLogger.info('日志系统测试：带上下文', { timestamp: Date.now() })
      
      results.tests.logging = {
        status: 'passed',
        message: '日志已输出到控制台'
      }
    } catch (error) {
      results.tests.logging = {
        status: 'failed',
        error: (error as Error).message
      }
    }

    // 测试 3: 缓存服务
    try {
      const cacheKey = 'test:verification:' + Date.now()
      const cacheValue = { message: '缓存测试', timestamp: Date.now() }
      
      await cache.set(cacheKey, cacheValue, 10)
      const cached = await cache.get(cacheKey)
      const hasKey = await cache.has(cacheKey)
      await cache.delete(cacheKey)
      
      results.tests.cache = {
        status: 'passed',
        set: 'success',
        get: cached !== null,
        has: hasKey,
        contentMatch: cached && (cached as any).message === cacheValue.message
      }
      
      logger.info('缓存服务测试通过')
    } catch (error) {
      results.tests.cache = {
        status: 'failed',
        error: (error as Error).message
      }
      logger.error('缓存服务测试失败', { error: (error as Error).message })
    }

    // 测试 4: 异步任务
    try {
      const job = await jobQueue.push('test:verification', {
        message: '异步任务测试',
        timestamp: Date.now()
      })
      
      const jobStatus = await jobQueue.getJob(job.id)
      
      results.tests.jobQueue = {
        status: 'passed',
        jobId: job.id,
        jobStatus: jobStatus?.status
      }
      
      logger.info('异步任务测试通过', { jobId: job.id })
    } catch (error) {
      results.tests.jobQueue = {
        status: 'failed',
        error: (error as Error).message
      }
      logger.error('异步任务测试失败', { error: (error as Error).message })
    }

    // 汇总结果
    const allPassed = Object.values(results.tests).every((test: any) => test.status === 'passed')
    results.overall = allPassed ? 'ALL_PASSED' : 'SOME_FAILED'
    
    if (allPassed) {
      logger.info('✅ 平台基础设施验证：全部通过', { tests: Object.keys(results.tests) })
    } else {
      logger.warn('⚠️ 平台基础设施验证：部分失败', { results })
    }

    return reply.status(200).send(results)
  })
}

