import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
import { z } from 'zod';
import { AppDataSource } from '@d8d/shared-utils';
import { authMiddleware } from '@d8d/auth-module-mt';
import { AuthContext } from '@d8d/shared-types';
import { PaymentMtService } from '../../services/payment.mt.service.js';
import { TriggerPaymentSuccessRequestSchema, TriggerPaymentSuccessResponseSchema } from '../../schemas/payment.mt.schema.js';

// 触发支付成功事件路由定义 - 多租户版本
const triggerPaymentSuccessRoute = createRoute({
  method: 'post',
  path: '/trigger-success',
  middleware: [authMiddleware],
  request: {
    body: {
      content: {
        'application/json': { schema: TriggerPaymentSuccessRequestSchema }
      }
    }
  },
  responses: {
    200: {
      description: '支付成功事件触发成功',
      content: { 'application/json': { schema: TriggerPaymentSuccessResponseSchema } }
    },
    400: {
      description: '参数错误',
      content: { 'application/json': { schema: z.object({ message: z.string() }) } }
    },
    401: {
      description: '未授权',
      content: { 'application/json': { schema: z.object({ message: z.string() }) } }
    },
    500: {
      description: '服务器错误',
      content: { 'application/json': { schema: z.object({ message: z.string() }) } }
    }
  }
});

const app = new OpenAPIHono<AuthContext>()
  .openapi(triggerPaymentSuccessRoute, async (c) => {
    try {
      const requestData = c.req.valid('json');
      const user = c.get('user');

      // 创建支付服务实例
      const paymentService = new PaymentMtService(AppDataSource);

      // 触发支付成功事件
      await paymentService.triggerPaymentSuccessEvent(
        user.tenantId,
        requestData.orderId
      );

      return c.json({
        success: true,
        message: '支付成功事件已触发，延迟打印任务已创建',
        orderId: requestData.orderId,
        tenantId: user.tenantId
      }, 200);
    } catch (error) {
      console.error('触发支付成功事件失败:', error);
      return c.json({
        success: false,
        message: error instanceof Error ? error.message : '触发支付成功事件失败',
        orderId: 0,
        tenantId: 0
      }, 500);
    }
  });

export default app;