import { OpenAPIHono } from '@hono/zod-openapi'
import { swaggerUI } from '@hono/swagger-ui'
import { errorHandler, initializeDataSource } from '@d8d/shared-utils'
import { userRoutes as userModuleRoutes, roleRoutes as roleModuleRoutes } from '@d8d/core-module/user-module'
import { authRoutes as authModuleRoutes, enterpriseAuthRoutes as enterpriseAuthModuleRoutes } from '@d8d/core-module/auth-module'
import { fileRoutes as fileModuleRoutes } from '@d8d/core-module/file-module'
import { AuthContext } from '@d8d/shared-types'
import { AppDataSource } from '@d8d/shared-utils'
import { Hono } from 'hono'
import { databaseBackup } from './utils/backup'
import { UserEntity, Role } from '@d8d/core-module/user-module'
import { File } from '@d8d/core-module/file-module'
import { SystemConfig } from '@d8d/core-module/system-config-module'
import { areasRoutes, adminAreasRoutes, AreaEntity } from '@d8d/geo-areas'
import { channelRoutes } from '@d8d/allin-channel-module'
import { Channel } from '@d8d/allin-channel-module/entities'
import { companyRoutes, companyStatisticsRoutes, companyEnterpriseRoutes } from '@d8d/allin-company-module'
import { Company } from '@d8d/allin-company-module/entities'
import { disabledPersonRoutes, personExtensionRoutes } from '@d8d/allin-disability-module'
import { DisabledPerson, DisabledBankCard, DisabledPhoto, DisabledRemark, DisabledVisit } from '@d8d/allin-disability-module/entities'
import { orderRoutes, enterpriseOrderRoutes } from '@d8d/allin-order-module'
import { EmploymentOrder, OrderPerson, OrderPersonAsset } from '@d8d/allin-order-module/entities'
import { platformRoutes } from '@d8d/allin-platform-module'
import { Platform } from '@d8d/allin-platform-module/entities'
import { salaryRoutes } from '@d8d/allin-salary-module'
import { SalaryLevel } from '@d8d/allin-salary-module/entities'
import { bankNameRoutes } from '@d8d/bank-names-module'
import { BankName } from '@d8d/bank-names-module'

initializeDataSource([
  UserEntity, Role, File, SystemConfig, AreaEntity,
  Channel,
  Company,
  DisabledPerson, DisabledBankCard, DisabledPhoto, DisabledRemark, DisabledVisit,
  EmploymentOrder, OrderPerson, OrderPersonAsset,
  Platform,
  SalaryLevel,
  BankName
])

if(!AppDataSource || !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', userModuleRoutes)
export const authRoutes = api.route('/api/v1/auth', authModuleRoutes)
export const fileApiRoutes = api.route('/api/v1/files', fileModuleRoutes)
export const roleRoutes = api.route('/api/v1/roles', roleModuleRoutes)
export const areaApiRoutes = api.route('/api/v1/areas', areasRoutes)
export const adminAreaApiRoutes = api.route('/api/v1/admin/areas', adminAreasRoutes)
export const channelApiRoutes = api.route('/api/v1/channel', channelRoutes)
export const companyApiRoutes = api.route('/api/v1/company', companyRoutes)
export const disabilityApiRoutes = api.route('/api/v1/disability', disabledPersonRoutes)
export const orderApiRoutes = api.route('/api/v1/order', orderRoutes)
export const platformApiRoutes = api.route('/api/v1/platform', platformRoutes)
export const salaryApiRoutes = api.route('/api/v1/salary', salaryRoutes)
export const bankNameApiRoutes = api.route('/api/v1/bank-names', bankNameRoutes)

// 企业用户专用路由（用人方小程序）
export const enterpriseAuthApiRoutes = api.route('/api/v1/yongren/auth', enterpriseAuthModuleRoutes)
export const enterpriseCompanyApiRoutes = api.route('/api/v1/yongren/company', companyEnterpriseRoutes)
export const enterpriseDisabilityApiRoutes = api.route('/api/v1/yongren/disability-person', personExtensionRoutes)
export const enterpriseOrderApiRoutes = api.route('/api/v1/yongren/order', enterpriseOrderRoutes)

export type AuthRoutes = typeof authRoutes
export type UserRoutes = typeof userRoutes
export type FileRoutes = typeof fileApiRoutes
export type RoleRoutes = typeof roleRoutes
export type AreaRoutes = typeof areaApiRoutes
export type AdminAreaRoutes = typeof adminAreaApiRoutes
export type ChannelRoutes = typeof channelApiRoutes
export type CompanyRoutes = typeof companyApiRoutes
export type DisabilityRoutes = typeof disabilityApiRoutes
export type OrderRoutes = typeof orderApiRoutes
export type PlatformRoutes = typeof platformApiRoutes
export type SalaryRoutes = typeof salaryApiRoutes
export type BankNameRoutes = typeof bankNameApiRoutes
export type EnterpriseAuthRoutes = typeof enterpriseAuthApiRoutes
export type EnterpriseCompanyRoutes = typeof enterpriseCompanyApiRoutes
export type EnterpriseDisabilityRoutes = typeof enterpriseDisabilityApiRoutes
export type EnterpriseOrderRoutes = typeof enterpriseOrderApiRoutes

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