import { OpenAPIHono } from '@hono/zod-openapi'
import { swaggerUI } from '@hono/swagger-ui'
import { errorHandler } from './utils/errorHandler'
import usersRouter from './api/users/index'
import authRoute from './api/auth/index'
import rolesRoute from './api/roles/index'
import fileRoute from './api/files/index'
import classroomDataRoutes from './api/classroom-data/index'
import submissionRecordsRoutes from './api/submission-records/index'
import stockDataRoutes from './api/stock-data/index'
import stockXunlianCodesRoutes from './api/stock-xunlian-codes/index'
import dateNotesRoutes from './api/date-notes/index'
import aliyunRoute from './api/aliyun/index'
import wechatRoutes from './api/auth/wechat/index'
import chatMessageRoutes from './api/chat-messages/index'
import vodRoutes from './api/vod/index'
import vodVideoRoutes from './api/vod-videos/index'
import { AuthContext } from './types/context'
import { AppDataSource } from './data-source'
import { Hono } from 'hono'

const app = new Hono();
const api = new OpenAPIHono<AuthContext>()

api.onError(errorHandler)

// Rate limiting
api.use('/api/v1/*', async (c, next) => {
  const ip = c.req.header('x-forwarded-for') || c.req.header('cf-connecting-ip')
  // 实现速率限制逻辑
  await next()
})

// 数据库初始化中间件
api.use('/api/v1/*', async (c, next) => {
  if(!AppDataSource.isInitialized) {
    await AppDataSource.initialize();
  }
  await next();
})

// 注册Bearer认证方案
api.openAPIRegistry.registerComponent('securitySchemes','bearerAuth',{
  type:'http',
  scheme:'bearer',
  bearerFormat:'JWT',
  description:'使用JWT进行认证'
})

// OpenAPI documentation endpoint
if(!import.meta.env.PROD){
  api.doc31('/doc', {
    openapi: '3.1.0',
    info: {
      title: 'API Documentation',
      version: '1.0.0'
    },
    security: [{
      bearerAuth: []
    }]
    // servers: [{ url: '/api/v1' }]
  })

  app.get('/ui', swaggerUI({
    url: '/doc',
    persistAuthorization: true,
    manuallySwaggerUIHtml: (asset) => `
      <div>
        <div id="swagger-ui"></div>
        <link rel="stylesheet" href="https://ai-oss.d8d.fun/swagger-ui-dist/swagger-ui.css" />
        <script src="https://ai-oss.d8d.fun/swagger-ui-dist/swagger-ui-bundle.js" crossorigin="anonymous"></script>
        <script>
          window.onload = () => {
            window.ui = SwaggerUIBundle({
              dom_id: '#swagger-ui',
              url: '/doc',
              persistAuthorization: true
            })
          }
        </script>
      </div>
    `
  }))
}



const userRoutes = api.route('/api/v1/users', usersRouter)
const authRoutes = api.route('/api/v1/auth', authRoute)
const roleRoutes = api.route('/api/v1/roles', rolesRoute)
const fileRoutes = api.route('/api/v1/files', fileRoute)
const classroomDataApi = api.route('/api/v1/classroom-data', classroomDataRoutes)
const submissionRecordsApi = api.route('/api/v1/submission-records', submissionRecordsRoutes)
const stockDataApi = api.route('/api/v1/stock-data', stockDataRoutes)
const stockXunlianCodesApi = api.route('/api/v1/stock-xunlian-codes', stockXunlianCodesRoutes)
const dateNotesApi = api.route('/api/v1/date-notes', dateNotesRoutes)
const aliyunApi = api.route('/api/v1/aliyun', aliyunRoute)
const wechatAuthApi = api.route('/api/v1/auth/wechat', wechatRoutes)
const chatMessageApi = api.route('/api/v1/chat-messages', chatMessageRoutes)
const vodApi = api.route('/api/v1/vod', vodRoutes)
const vodVideoApi = api.route('/api/v1/vod-videos', vodVideoRoutes)

export type AuthRoutes = typeof authRoutes
export type UserRoutes = typeof userRoutes
export type RoleRoutes = typeof roleRoutes
export type FileRoutes = typeof fileRoutes
export type ClassroomDataRoutes = typeof classroomDataApi
export type SubmissionRecordsRoutes = typeof submissionRecordsApi
export type StockDataRoutes = typeof stockDataApi
export type StockXunlianCodesRoutes = typeof stockXunlianCodesApi
export type DateNotesRoutes = typeof dateNotesApi
export type AliyunRoutes = typeof aliyunApi
export type WechatAuthRoutes = typeof wechatAuthApi
export type ChatMessageRoutes = typeof chatMessageApi
export type VodRoutes = typeof vodApi
export type VodVideoRoutes = typeof vodVideoApi

app.route('/', api)
export default app