import { OpenAPIHono } from '@hono/zod-openapi'
import { swaggerUI } from '@hono/swagger-ui'
import { errorHandler, initializeDataSource } from '@d8d/shared-utils'
import { userRoutesMt as userModuleRoutes, roleRoutesMt as roleModuleRoutes } from '@d8d/user-module-mt'
import { authRoutes as authModuleRoutes } from '@d8d/auth-module-mt'
import { fileRoutesMt as fileModuleRoutes } from '@d8d/file-module-mt'
import { AuthContext } from '@d8d/shared-types'
import { AppDataSource } from '@d8d/shared-utils'
import { Hono } from 'hono'
import { UserEntityMt, RoleMt } from '@d8d/user-module-mt'
import { FileMt } from '@d8d/file-module-mt'

// 导入已实现的包实体
import { AreaEntityMt } from '@d8d/geo-areas-mt'
import { PaymentMtEntity } from '@d8d/mini-payment-mt'
import { Advertisement, AdvertisementType } from '@d8d/advertisements-module-mt'
import { DeliveryAddressMt } from '@d8d/delivery-address-module-mt'
import { GoodsMt, GoodsCategoryMt } from '@d8d/goods-module-mt'
import { MerchantMt } from '@d8d/merchant-module-mt'
import { OrderMt, OrderGoodsMt, OrderRefundMt } from '@d8d/orders-module-mt'
import { SupplierMt } from '@d8d/supplier-module-mt'

if(!AppDataSource || !AppDataSource.isInitialized) {
  initializeDataSource([
    // 已实现的包实体
    UserEntityMt, RoleMt, FileMt,
    AreaEntityMt, PaymentMtEntity,
    Advertisement, AdvertisementType,
    DeliveryAddressMt,
    GoodsMt, GoodsCategoryMt,
    MerchantMt,
    OrderMt, OrderGoodsMt, OrderRefundMt,
    SupplierMt
  ])
  await AppDataSource.initialize();
  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)

// 导入已实现的包路由
import { areasRoutesMt, adminAreasRoutesMt } from '@d8d/geo-areas-mt'
import { PaymentMtRoutes as PaymentRoutes } from '@d8d/mini-payment-mt'
import { advertisementRoutes, advertisementTypeRoutes } from '@d8d/advertisements-module-mt'
import { userDeliveryAddressRoutesMt as userDeliveryAddressRoutes } from '@d8d/delivery-address-module-mt'
import { adminGoodsCategoriesRoutesMt as adminGoodsCategoriesRoutes, adminGoodsRoutesMt as adminGoodsRoutes } from '@d8d/goods-module-mt'
import { userMerchantRoutes as merchantRoutes } from '@d8d/merchant-module-mt'
import { userOrderRoutes, userOrderItemsRoutes, userRefundsRoutes } from '@d8d/orders-module-mt'
import { userSupplierRoutes } from '@d8d/supplier-module-mt'


// 注册已实现的包路由
export const areaApiRoutes = api.route('/api/v1/areas', areasRoutesMt)
export const adminAreaApiRoutes = api.route('/api/v1/admin/areas', adminAreasRoutesMt)
export const paymentApiRoutes = api.route('/api/v1/payments', PaymentRoutes)
export const advertisementApiRoutes = api.route('/api/v1/advertisements', advertisementRoutes)
export const advertisementTypeApiRoutes = api.route('/api/v1/advertisement-types', advertisementTypeRoutes)
export const deliveryAddressApiRoutes = api.route('/api/v1/delivery-addresses', userDeliveryAddressRoutes)
export const goodsCategoryApiRoutes = api.route('/api/v1/goods-categories', adminGoodsCategoriesRoutes)
export const goodsApiRoutes = api.route('/api/v1/goods', adminGoodsRoutes)
export const merchantApiRoutes = api.route('/api/v1/merchants', merchantRoutes)
export const orderApiRoutes = api.route('/api/v1/orders', userOrderRoutes)
export const orderGoodsApiRoutes = api.route('/api/v1/orders-goods', userOrderItemsRoutes)
export const orderRefundApiRoutes = api.route('/api/v1/orders-refund', userRefundsRoutes)
export const supplierApiRoutes = api.route('/api/v1/suppliers', userSupplierRoutes)


export type AuthRoutes = typeof authRoutes
export type UserRoutes = typeof userRoutes
export type FileRoutes = typeof fileApiRoutes
export type RoleRoutes = typeof roleRoutes
export type AdvertisementRoutes = typeof advertisementApiRoutes
export type AdvertisementTypeRoutes = typeof advertisementTypeApiRoutes
export type GoodsCategoryRoutes = typeof goodsCategoryApiRoutes
export type GoodsRoutes = typeof goodsApiRoutes
export type SupplierRoutes = typeof supplierApiRoutes
export type MerchantRoutes = typeof merchantApiRoutes
export type DeliveryAddressRoutes = typeof deliveryAddressApiRoutes
export type OrderRoutes = typeof orderApiRoutes
export type OrderGoodsRoutes = typeof orderGoodsApiRoutes
export type OrderRefundRoutes = typeof orderRefundApiRoutes
export type AreaRoutes = typeof areaApiRoutes
export type AdminAreaRoutes = typeof adminAreaApiRoutes

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