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 { OrderMtService } from '../../services/order.mt.service.js';

// 支付记录查询路由定义 - 多租户版本
const paymentRecordRoute = createRoute({
  method: 'get',
  path: '/:orderId/payment-record',
  middleware: [authMiddleware],
  request: {
    params: z.object({
      orderId: z.string().transform(val => parseInt(val)).pipe(z.number().int().positive())
    })
  },
  responses: {
    200: {
      description: '支付记录查询成功',
      content: {
        'application/json': {
          schema: z.object({
            success: z.boolean(),
            data: z.object({
              outTradeNo: z.string().nullable(),
              wechatTransactionId: z.string().nullable(),
              paymentStatus: z.string(),
              exists: z.boolean()
            }).nullable(),
            message: z.string()
          })
        }
      }
    },
    400: {
      description: '参数错误',
      content: {
        'application/json': {
          schema: z.object({
            success: z.boolean(),
            message: z.string()
          })
        }
      }
    },
    401: {
      description: '未授权',
      content: {
        'application/json': {
          schema: z.object({
            success: z.boolean(),
            message: z.string()
          })
        }
      }
    },
    404: {
      description: '订单不存在',
      content: {
        'application/json': {
          schema: z.object({
            success: z.boolean(),
            message: z.string()
          })
        }
      }
    },
    500: {
      description: '服务器错误',
      content: {
        'application/json': {
          schema: z.object({
            success: z.boolean(),
            message: z.string()
          })
        }
      }
    }
  }
});

const app = new OpenAPIHono<AuthContext>()
  .openapi(paymentRecordRoute, async (c) => {
    try {
      const { orderId } = c.req.valid('param');
      const user = c.get('user');

      // 创建订单服务实例
      const orderService = new OrderMtService(AppDataSource);

      // 首先验证订单是否存在且属于当前用户
      const orderRepository = AppDataSource.getRepository('OrderMt');
      const order = await orderRepository.findOne({
        where: {
          id: orderId,
          tenantId: user.tenantId,
          userId: user.id
        }
      });

      if (!order) {
        return c.json({
          success: false,
          message: '订单不存在或无权访问'
        }, 404);
      }

      // 查询支付记录信息
      const paymentInfo = await orderService.getPaymentInfoByOrderId(
        user.tenantId,
        orderId,
        user.id
      );

      return c.json({
        success: true,
        data: paymentInfo,
        message: paymentInfo.exists ? '支付记录查询成功' : '未找到支付记录'
      }, 200);

    } catch (error) {
      console.error('支付记录查询失败:', error);
      return c.json({
        success: false,
        message: error instanceof Error ? error.message : '支付记录查询失败'
      }, 500);
    }
  });

export default app;