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 UploadShippingInfoSchema = z.object({
  orderId: z.string().min(1, '订单ID不能为空'),
  deliveryType: z.number().int().min(1, '发货方式最小为1').max(4, '发货方式最大为4').describe('发货方式：1-物流快递, 2-同城配送, 3-虚拟发货, 4-用户自提'),
  expressInfo: z.object({
    deliveryId: z.string().min(1, '快递公司ID不能为空'),
    waybillId: z.string().min(1, '快递单号不能为空')
  }).optional(),
  localDeliveryInfo: z.object({
    deliveryName: z.string().min(1, '配送员姓名不能为空'),
    deliveryPhone: z.string().min(1, '配送员手机号不能为空')
  }).optional(),
  isAllDelivered: z.boolean().default(true),
  itemDesc: z.string().optional().describe('商品描述，最多110个字'),
  tenantId: z.number().optional()
});

// 发货信息录入响应Schema
const UploadShippingInfoResponseSchema = z.object({
  success: z.boolean(),
  message: z.string(),
  data: z.any().optional(),
  error: z.any().optional()
});

const uploadShippingInfoRoute = createRoute({
  method: 'post',
  path: '/upload-shipping-info',
  request: {
    body: {
      content: {
        'application/json': {
          schema: UploadShippingInfoSchema
        }
      }
    }
  },
  responses: {
    200: {
      description: '发货信息录入成功',
      content: {
        'application/json': {
          schema: UploadShippingInfoResponseSchema
        }
      }
    },
    400: {
      description: '参数错误',
      content: {
        'application/json': {
          schema: ErrorSchema
        }
      }
    },
    500: {
      description: '服务器错误',
      content: {
        'application/json': {
          schema: ErrorSchema
        }
      }
    }
  }
});

const app = new OpenAPIHono().openapi(uploadShippingInfoRoute, async (c) => {
  try {
    const miniAuthService = new MiniAuthService(AppDataSource);
    const { orderId, deliveryType, expressInfo, localDeliveryInfo, isAllDelivered, itemDesc, tenantId } = c.req.valid('json');

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

    console.log('收到发货信息录入请求:', {
      orderId,
      deliveryType,
      expressInfo,
      localDeliveryInfo,
      isAllDelivered,
      itemDesc,
      tenantId,
      timestamp
    });

    // 调用服务录入发货信息
    const result = await miniAuthService.uploadShippingInfo({
      orderId,
      deliveryType,
      expressInfo,
      localDeliveryInfo,
      isAllDelivered,
      itemDesc,
      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;