import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
import { z } from '@hono/zod-openapi';
import { MiniAuthService } from '../services/index.mt';
import { AppDataSource } from '@d8d/shared-utils';
import { ErrorSchema } from '@d8d/shared-utils';

// 微信小店发货请求Schema
const SendWechatShopDeliverySchema = z.object({
  orderId: z.number().int().positive('订单ID必须为正整数'),
  orderNo: z.string().min(1, '订单号不能为空'),
  deliveryType: z.number().int().min(1, '发货方式最小为1').max(4, '发货方式最大为4'),
  deliveryCompany: z.string().nullable().optional(),
  deliveryNo: z.string().nullable().optional(),
  tenantId: z.number().optional()
});

// 微信小店发货响应Schema
const SendWechatShopDeliveryResponseSchema = z.object({
  success: z.boolean(),
  message: z.string(),
  data: z.any().optional(),
  error: z.any().optional()
});

const sendWechatShopDeliveryRoute = createRoute({
  method: 'post',
  path: '/send-wechat-shop-delivery',
  request: {
    body: {
      content: {
        'application/json': {
          schema: SendWechatShopDeliverySchema
        }
      }
    }
  },
  responses: {
    200: {
      description: '微信小店发货成功',
      content: {
        'application/json': {
          schema: SendWechatShopDeliveryResponseSchema
        }
      }
    },
    400: {
      description: '参数错误',
      content: {
        'application/json': {
          schema: ErrorSchema
        }
      }
    },
    500: {
      description: '服务器错误',
      content: {
        'application/json': {
          schema: ErrorSchema
        }
      }
    }
  }
});

const app = new OpenAPIHono().openapi(sendWechatShopDeliveryRoute, async (c) => {
  try {
    const miniAuthService = new MiniAuthService(AppDataSource);
    const { orderId, orderNo, deliveryType, deliveryCompany, deliveryNo, tenantId } = c.req.valid('json');

    // 调试输出
    const timestamp = new Date().toISOString();

    console.log('收到微信小店发货请求:', {
      orderId,
      orderNo,
      deliveryType,
      deliveryCompany,
      deliveryNo,
      tenantId,
      timestamp
    });

    // 注意：这里需要根据实际情况获取微信小店订单ID
    // 目前代码中假设orderNo就是微信小店订单ID，实际项目中可能需要从数据库查询映射关系
    const wechatOrderId = orderNo; // 临时使用orderNo作为微信小店订单ID

    // 调用服务发送微信小店发货
    const result = await miniAuthService.sendWechatShopDelivery({
      wechatOrderId,
      deliveryCompany: deliveryCompany || undefined,
      deliveryNo: deliveryNo || undefined,
      tenantId
    });

    return c.json({
      success: true,
      message: '微信小店发货成功',
      data: result
    }, 200);

  } catch (error) {
    console.error('微信小店发货失败:', error);

    const errorMessage = error instanceof Error ? error.message : '微信小店发货失败';
    const errorCode = (error as any)?.code || 500;

    return c.json({
      success: false,
      message: errorMessage,
      error: error instanceof Error ? error.stack : error
    }, errorCode);
  }
});

export default app;