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';

// 支付状态查询路由定义 - 多租户版本
const paymentStatusRoute = createRoute({
  method: 'get',
  path: '/',
  middleware: [authMiddleware],
  request: {
    query: z.object({
      orderId: z.string().transform(val => parseInt(val)).pipe(z.number().int().positive())
    })
  },
  responses: {
    200: {
      description: '支付状态查询成功',
      content: { 'application/json': { schema: z.object({ paymentStatus: z.string() }) } }
    },
    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(paymentStatusRoute, async (c) => {
    try {
      const { orderId } = c.req.valid('query');
      const user = c.get('user');

      // 创建支付服务实例
      const paymentService = new PaymentMtService(AppDataSource);
      const paymentStatus = await paymentService.getPaymentStatus(orderId, user.tenantId);

      return c.json({
        paymentStatus
      }, 200);
    } catch (error) {
      console.error('支付状态查询失败:', error);
      return c.json({
        message: error instanceof Error ? error.message : '支付状态查询失败'
      }, 500);
    }
  });

export default app;