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 membershipPlanRoute from './api/membership-plans/index'
import paymentRoute from './api/payments/index'
import templateRoute from './api/templates/index'
import publicTemplateRoute from './api/public/templates/index'
import publicSettingsRoute from './api/public/settings/index'
import settingsRoute from './api/settings/index'
import documentsRoute from './api/documents/index'
import solutionDesignsRoute from './api/solution-designs/index'
import consultationRequestRoutes from './api/consultation-requests/index'
import publicConsultationRequestRoutes from './api/public/consultation-requests/index'
import { AuthContext } from './types/context'
import { AppDataSource } from './data-source'
import { Hono } from 'hono'
import { databaseBackup } from './utils/backup'

if(!AppDataSource.isInitialized) {
  await AppDataSource.initialize();
  console.log('数据库初始化完成')

  // 启动数据库备份调度
  databaseBackup.startScheduledBackups();
  console.log('数据库备份调度已启动');
}

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

api.onError(errorHandler)

// Rate limiting
api.use('/api/v1/*', async (_, next) => {
  // 实现速率限制逻辑
  await next()
})

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

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

// OpenAPI documentation endpoint
// !import.meta.env.PROD
if(1){
  // api.doc31('/doc', {
  //   openapi: '3.1.0',
  //   info: {
  //     title: 'API Documentation',
  //     version: '1.0.0'
  //   },
  //   security: [{
  //     bearerAuth: []
  //   }]
  //   // servers: [{ url: '/api/v1' }]
  // })
  api.get('/doc', (c) => {
    const config = {
      openapi: '3.1.0',
      info: {
        title: 'API Documentation',
        version: '1.0.0'
      },
      security: [{
        bearerAuth: []
      }]
      // servers: [{ url: '/api/v1' }]
    };
    try {
      const document = api.getOpenAPI31Document(config);
      return c.json(document);
    } catch (e: any) {  
      return c.json({  
        error: 'OpenAPI document generation failed',  
        message: e.message || 'Unknown error',  
        stack: e.stack  
      }, 500)  
    }
  })

  app.get('/ui', swaggerUI({
    url: '/doc',
    persistAuthorization: true,
    manuallySwaggerUIHtml: () => `
      <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>
    `
  }))
}



export const userRoutes = api.route('/api/v1/users', usersRouter)
export const authRoutes = api.route('/api/v1/auth', authRoute)
export const roleRoutes = api.route('/api/v1/roles', rolesRoute)
export const fileRoutes = api.route('/api/v1/files', fileRoute)
export const membershipPlanRoutes = api.route('/api/v1/membership-plans', membershipPlanRoute)
export const paymentRoutes = api.route('/api/v1/payments', paymentRoute)
export const templateRoutes = api.route('/api/v1/templates', templateRoute)
export const publicTemplateRoutes = api.route('/api/v1/public/templates', publicTemplateRoute)
export const publicSettingsRoutes = api.route('/api/v1/public/settings', publicSettingsRoute)
export const settingsRoutes = api.route('/api/v1/settings', settingsRoute)
export const documentsRoutes = api.route('/api/v1/documents', documentsRoute)
export const solutionDesignsRoutes = api.route('/api/v1/solution-designs', solutionDesignsRoute)
export const consultationRequestRoutes = api.route('/api/v1/consultation-requests', consultationRequestRoutes)
export const publicConsultationRequestRoutes = api.route('/api/v1/public/consultation-requests', publicConsultationRequestRoutes)

export type AuthRoutes = typeof authRoutes
export type UserRoutes = typeof userRoutes
export type RoleRoutes = typeof roleRoutes
export type FileRoutes = typeof fileRoutes
export type MembershipPlanRoutes = typeof membershipPlanRoutes
export type PaymentRoutes = typeof paymentRoutes
export type TemplateRoutes = typeof templateRoutes
export type PublicTemplateRoutes = typeof publicTemplateRoutes
export type PublicSettingsRoutes = typeof publicSettingsRoutes
export type SettingsRoutes = typeof settingsRoutes
export type DocumentsRoutes = typeof documentsRoutes
export type SolutionDesignsRoutes = typeof solutionDesignsRoutes
export type ConsultationRequestRoutes = typeof consultationRequestRoutes
export type PublicConsultationRequestRoutes = typeof publicConsultationRequestRoutes

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