import { OpenAPIHono } from '@hono/zod-openapi'
import { swaggerUI } from '@hono/swagger-ui'
import { databaseBackup } from './utils/backup'
import { errorHandler, initializeDataSource } from '@d8d/shared-utils'
import { userRoutesMt as userModuleRoutes, roleRoutesMt as roleModuleRoutes } from '@d8d/core-module-mt/user-module-mt'
import { authRoutes as authModuleRoutes } from '@d8d/core-module-mt/auth-module-mt'
import { fileRoutesMt as fileModuleRoutes } from '@d8d/core-module-mt/file-module-mt'
import { tenantRoutes } from '@d8d/tenant-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 { TenantEntityMt } from '@d8d/tenant-module-mt'
import { SystemConfigMt } from '@d8d/core-module-mt/system-config-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'
import { CreditBalanceMt, CreditBalanceLogMt } from '@d8d/credit-balance-module-mt'
import { creditBalanceRoutes as creditBalanceModuleRoutes } from '@d8d/credit-balance-module-mt'
import { FeieConfigMt, FeiePrintTaskMt, FeiePrinterMt } from '@d8d/feie-printer-module-mt'
import { FeieMtRoutes } from '@d8d/feie-printer-module-mt'

initializeDataSource([
  // 已实现的包实体
  UserEntityMt, RoleMt, FileMt,
  TenantEntityMt,
  AreaEntityMt, PaymentMtEntity,
  Advertisement, AdvertisementType,
  DeliveryAddressMt,
  GoodsMt, GoodsCategoryMt,
  MerchantMt,
  OrderMt, OrderGoodsMt, OrderRefundMt,
  SupplierMt, SystemConfigMt,
  CreditBalanceMt, CreditBalanceLogMt,
  FeieConfigMt, FeiePrintTaskMt, FeiePrinterMt
])

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

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

// 初始化飞鹅打印防退款延迟调度器
try {
  const { DelaySchedulerService } = await import('@d8d/feie-printer-module-mt');
  const { FeieMtRoutes } = await import('@d8d/feie-printer-module-mt');

  // 获取所有有飞鹅配置的租户
  const systemConfigRepository = AppDataSource.getRepository('feie_config_mt');
  const configs = await systemConfigRepository.find({
    where: {
      configKey: 'feie.api.user'
    }
  });

  // 为每个有配置的租户启动调度器
  for (const config of configs) {
    const tenantId = config.tenantId;

    // 动态获取飞鹅配置
    const configKeys = [
      'feie.api.user',
      'feie.api.ukey',
      'feie.api.base_url',
      'feie.api.timeout',
      'feie.api.max_retries'
    ];

    const tenantConfigs = await systemConfigRepository.find({
      where: {
        tenantId,
        configKey: configKeys
      }
    });

    const configMap: Record<string, string> = {};
    tenantConfigs.forEach((config: any) => {
      configMap[config.configKey] = config.configValue;
    });

    const user = configMap['feie.api.user'];
    const ukey = configMap['feie.api.ukey'];

    if (user && ukey) {
      const feieConfig = {
        user,
        ukey,
        baseUrl: configMap['feie.api.base_url'] || 'https://api.feieyun.cn/Api/Open/',
        timeout: parseInt(configMap['feie.api.timeout'] || '10000', 10),
        maxRetries: parseInt(configMap['feie.api.max_retries'] || '3', 10)
      };

      const delaySchedulerService = new DelaySchedulerService(AppDataSource, feieConfig, tenantId);
      await delaySchedulerService.start();
      console.log(`[租户${tenantId}] 防退款延迟打印调度器已启动`);
    }
  }

  console.log('飞鹅打印防退款延迟调度器初始化完成');
} catch (error) {
  console.warn('飞鹅打印防退款延迟调度器初始化失败，延迟打印功能可能不可用:', error);
}

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 tenantApiRoutes = api.route('/api/v1/tenants', tenantRoutes)

// 导入已实现的包路由
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, adminDeliveryAddressRoutesMt as adminDeliveryAddressRoutes } from '@d8d/delivery-address-module-mt'
import {
  adminGoodsCategoriesRoutesMt as adminGoodsCategoriesRoutes,
  adminGoodsRoutesMt as adminGoodsRoutes,
  userGoodsCategoriesRoutesMt,
  publicGoodsRoutesMt,
  publicGoodsRandomRoutesMt
} from '@d8d/goods-module-mt'
import { userMerchantRoutes as merchantRoutes } from '@d8d/merchant-module-mt'
import { 
  userOrderRoutes, 
  // userOrderItemsRoutes, userRefundsRoutes, 
  adminOrderRoutes, adminOrderItemsRoutes, adminRefundsRoutes } from '@d8d/orders-module-mt'
import { userSupplierRoutes } from '@d8d/supplier-module-mt'
import { systemConfigRoutesMt } from '@d8d/core-module-mt/system-config-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 adminDeliveryAddressApiRoutes = api.route('/api/v1/admin/delivery-addresses', adminDeliveryAddressRoutes)
export const goodsCategoryApiRoutes = api.route('/api/v1/goods-categories', userGoodsCategoriesRoutesMt)
export const adminGoodsCategoryApiRoutes = api.route('/api/v1/admin/goods-categories', adminGoodsCategoriesRoutes)
export const adminGoodsApiRoutes = api.route('/api/v1/admin/goods', adminGoodsRoutes)
export const goodsApiRoutes = api.route('/api/v1/goods', publicGoodsRoutesMt)
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 creditBalanceApiRoutes = api.route('/api/v1/credit-balance', creditBalanceModuleRoutes)

export const adminOrderApiRoutes = api.route('/api/v1/admin/orders', adminOrderRoutes)
export const adminOrderGoodsApiRoutes = api.route('/api/v1/admin/orders-goods', adminOrderItemsRoutes)
export const adminOrderRefundApiRoutes = api.route('/api/v1/admin/orders-refund', adminRefundsRoutes)
export const supplierApiRoutes = api.route('/api/v1/suppliers', userSupplierRoutes)
export const adminSystemConfigApiRoutes = api.route('/api/v1/admin/system-configs', systemConfigRoutesMt)

// 创建飞鹅打印路由
export const feieApiRoutes = api.route('/api/v1/feie', FeieMtRoutes)


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 AdminDeliveryAddressRoutes = typeof adminDeliveryAddressApiRoutes
export type OrderRoutes = typeof orderApiRoutes
// export type OrderGoodsRoutes = typeof orderGoodsApiRoutes
// export type OrderRefundRoutes = typeof orderRefundApiRoutes
export type AdminOrderRoutes = typeof adminOrderApiRoutes
export type AdminOrderGoodsRoutes = typeof adminOrderGoodsApiRoutes
export type AdminOrderRefundRoutes = typeof adminOrderRefundApiRoutes
export type AreaRoutes = typeof areaApiRoutes
export type AdminAreaRoutes = typeof adminAreaApiRoutes
export type PaymentRoutes = typeof paymentApiRoutes
export type CreditBalanceRoutes = typeof creditBalanceApiRoutes
export type FeieRoutes = typeof feieApiRoutes

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