import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
import { z } from 'zod';
import { AppDataSource } from '@d8d/shared-utils';
import { PaymentMtService } from '../../services/payment.mt.service.js';

// 支付回调路由定义 - 多租户版本
const paymentCallbackRoute = createRoute({
  method: 'post',
  path: '/',
  request: {
    body: {
      content: {
        'text/plain': { schema: z.string() }
      }
    }
  },
  responses: {
    200: {
      description: '回调处理成功',
      content: { 'text/plain': { schema: z.string() } }
    },
    400: {
      description: '回调数据错误',
      content: { 'application/json': { schema: z.object({ message: z.string() }) } }
    },
    500: {
      description: '服务器错误',
      content: { 'text/plain': { schema: z.string() } }
    }
  }
});

const app = new OpenAPIHono()
  .openapi(paymentCallbackRoute, async (c) => {
    try {
      // 获取原始请求体（用于签名验证）
      const rawBody = await c.req.text();

      console.log('原始请求体', rawBody)

      // 解析回调数据
      const callbackData = JSON.parse(rawBody);

      // 获取微信支付回调头信息
      const headers = {
        'wechatpay-timestamp': c.req.header('wechatpay-timestamp') || '',
        'wechatpay-nonce': c.req.header('wechatpay-nonce') || '',
        'wechatpay-signature': c.req.header('wechatpay-signature') || '',
        'wechatpay-serial': c.req.header('wechatpay-serial') || ''
      };

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

      // 处理支付回调
      await paymentService.handlePaymentCallback(callbackData, headers, rawBody);

      // 返回成功响应给微信支付
      return c.text('SUCCESS', 200);
    } catch (error) {
      console.error('支付回调处理失败:', error);
      // 返回失败响应给微信支付
      return c.text('FAIL', 500);
    }
  });

export default app;