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/user-module'
import { authRoutes as authModuleRoutes } from '@d8d/auth-module'
import { fileRoutes as fileModuleRoutes } from '@d8d/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/user-module'
import { File } from '@d8d/file-module'

// 导入其他实体（暂时保留在server包中）
import { Advertisement } from './modules/advertisements/advertisement.entity'
import { AdvertisementType } from './modules/advertisements/advertisement-type.entity'
import { GoodsCategory } from './modules/goods/goods-category.entity'
import { Goods } from './modules/goods/goods.entity'
import { City } from './modules/system/city.entity'
import { Config } from './modules/system/config.entity'
import { ExpressCompany } from './modules/logistics/express-company.entity'
import { Organization } from './modules/organization/organization.entity'
import { Supplier } from './modules/supplier/supplier.entity'
import { Card } from './modules/card/card.entity'
import { Agent } from './modules/agent/agent.entity'
import { Merchant } from './modules/merchant/merchant.entity'
import { UserCard } from './modules/user-cards/user-card.entity'
import { UserCardBalanceRecord } from './modules/user-card-balance-records/user-card-balance-record.entity'
import { DeliveryAddress } from './modules/delivery-address/delivery-address.entity'
import { Order } from './modules/orders/order.entity'
import { OrderGoods } from './modules/orders/order-goods.entity'
import { OrderRefund } from './modules/orders/order-refund.entity'

if(!AppDataSource || !AppDataSource.isInitialized) {
  initializeDataSource([
    UserEntity, Role, File,
    Advertisement, AdvertisementType, GoodsCategory, Goods, City, Config,
    ExpressCompany, Organization, Supplier, Card, Agent, Merchant,
    UserCard, UserCardBalanceRecord, DeliveryAddress, Order, OrderGoods, OrderRefund
  ])
  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)

// 导入并注册其他路由（暂时保留在server包中）
import advertisementRoutes from './api/advertisements/index'
import advertisementTypeRoutes from './api/advertisement-types/index'
import goodsCategoryRoutes from './api/goods-categories/index'
import goodsRoutes from './api/goods/index'
import cityRoutes from './api/cities/index'
import configRoutes from './api/configs/index'
import expressCompanyRoutes from './api/express-companies/index'
import organizationRoutes from './api/organizations/index'
import supplierRoutes from './api/suppliers/index'
import cardRoutes from './api/cards/index'
import agentRoutes from './api/agents/index'
import merchantRoutes from './api/merchants/index'
import userCardRoutes from './api/user-cards/index'
import userCardBalanceRecordRoutes from './api/user-card-balance-records/index'
import deliveryAddressRoutes from './api/delivery-address/index'
import orderRoutes from './api/orders/index'
import orderGoodsRoutes from './api/orders-goods/index'
import orderRefundRoutes from './api/orders-refund/index'

export const advertisementApiRoutes = api.route('/api/v1/advertisements', advertisementRoutes)
export const advertisementTypeApiRoutes = api.route('/api/v1/advertisement-types', advertisementTypeRoutes)
export const goodsCategoryApiRoutes = api.route('/api/v1/goods-categories', goodsCategoryRoutes)
export const goodsApiRoutes = api.route('/api/v1/goods', goodsRoutes)
export const cityApiRoutes = api.route('/api/v1/cities', cityRoutes)
export const configApiRoutes = api.route('/api/v1/configs', configRoutes)
export const expressCompanyApiRoutes = api.route('/api/v1/express-companies', expressCompanyRoutes)
export const organizationApiRoutes = api.route('/api/v1/organizations', organizationRoutes)
export const supplierApiRoutes = api.route('/api/v1/suppliers', supplierRoutes)
export const cardApiRoutes = api.route('/api/v1/cards', cardRoutes)
export const agentApiRoutes = api.route('/api/v1/agents', agentRoutes)
export const merchantApiRoutes = api.route('/api/v1/merchants', merchantRoutes)
export const userCardApiRoutes = api.route('/api/v1/user-cards', userCardRoutes)
export const userCardBalanceRecordApiRoutes = api.route('/api/v1/user-card-balance-records', userCardBalanceRecordRoutes)
export const deliveryAddressApiRoutes = api.route('/api/v1/delivery-addresses', deliveryAddressRoutes)
export const orderApiRoutes = api.route('/api/v1/orders', orderRoutes)
export const orderGoodsApiRoutes = api.route('/api/v1/orders-goods', orderGoodsRoutes)
export const orderRefundApiRoutes = api.route('/api/v1/orders-refund', orderRefundRoutes)

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 CityRoutes = typeof cityApiRoutes
export type ConfigRoutes = typeof configApiRoutes
export type ExpressCompanyRoutes = typeof expressCompanyApiRoutes
export type OrganizationRoutes = typeof organizationApiRoutes
export type SupplierRoutes = typeof supplierApiRoutes
export type CardRoutes = typeof cardApiRoutes
export type AgentRoutes = typeof agentApiRoutes
export type MerchantRoutes = typeof merchantApiRoutes
export type UserCardRoutes = typeof userCardApiRoutes
export type UserCardBalanceRecordRoutes = typeof userCardBalanceRecordApiRoutes
export type DeliveryAddressRoutes = typeof deliveryAddressApiRoutes
export type OrderRoutes = typeof orderApiRoutes
export type OrderGoodsRoutes = typeof orderGoodsApiRoutes
export type OrderRefundRoutes = typeof orderRefundApiRoutes

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