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 fileRoutes from './api/files/index'
import { activitiesRoutes as adminActivitiesRoutes } from './api/admin/activities'
import { routesRoutes as adminRoutesRoutes } from './api/admin/routes'
import areasRoutes from './api/admin/areas'
import locationsRoutes from './api/admin/locations'
import routesRoutes from './api/routes'
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 fileApiRoutes = api.route('/api/v1/files', fileRoutes)
export const adminActivitiesRoutesExport = api.route('/api/v1/admin/activities', adminActivitiesRoutes)
export const adminRoutesRoutesExport = api.route('/api/v1/admin/routes', adminRoutesRoutes)
export const adminAreasRoutesExport = api.route('/api/v1/admin/areas', areasRoutes)
export const adminLocationsRoutesExport = api.route('/api/v1/admin/locations', locationsRoutes)
export const routesRoutesExport = api.route('/api/v1/routes', routesRoutes)

export type AuthRoutes = typeof authRoutes
export type UserRoutes = typeof userRoutes
export type RoleRoutes = typeof roleRoutes
export type FileRoutes = typeof fileApiRoutes
export type AdminActivitiesRoutes = typeof adminActivitiesRoutesExport
export type AdminRoutesRoutes = typeof adminRoutesRoutesExport
export type AdminAreasRoutes = typeof adminAreasRoutesExport
export type AdminLocationsRoutes = typeof adminLocationsRoutesExport
export type RoutesRoutes = typeof routesRoutesExport

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