import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
import { z } from 'zod';
import { AppDataSource, ErrorSchema } 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 updateOrderPaymentStatusRoute = createRoute({
  method: 'post',
  path: '/updateOrderStatus',
  middleware: [authMiddleware],
  request: {
    body: {
      content: {
        'application/json': {
          schema: z.object({
            orderId: z.number().int().positive(),
            payState: z.number().int().min(0).max(5) // 0未支付、1支付中、2支付成功、3已退款、4支付失败、5订单关闭
          })
        }
      }
    }
  },
  responses: {
    200: {
      description: '订单支付状态更新成功',
      content: {
        'application/json': {
          schema: z.object({
            success: z.boolean(),
            message: z.string()
          })
        }
      }
    },
    400: {
      description: '请求参数错误',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    403: {
      description: '权限不足',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    404: {
      description: '订单不存在',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    500: {
      description: '服务器内部错误',
      content: { 'application/json': { schema: ErrorSchema } }
    }
  }
});

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

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

      // 更新订单支付状态
      await paymentService.updateOrderPaymentStatus(user.tenantId, orderId, payState);

      return c.json({
        success: true,
        message: '订单支付状态更新成功'
      }, 200);
    } catch (error) {
      console.error('订单支付状态更新失败:', error);

      // 根据错误类型返回不同的状态码
      if (error instanceof Error) {
        if (error.message.includes('订单不存在')) {
          return c.json(
            { code: 404, message: error.message },
            404
          );
        }
      }

      return c.json(
        { code: 500, message: error instanceof Error ? error.message : '订单支付状态更新失败' },
        500
      );
    }
  });

export default app;