import { NextFunction, Request, Response } from 'express';
import { z } from 'zod';
import { PublishService } from '../../services/PublishService';
import { logger } from '../../utils/logger';

export class PublishController {
  /**
   * [CORE_INT_03] 提交商品发布请求
   */
  static async publish(req: Request, res: Response, next: NextFunction) {
    try {
      const schema = z.object({
        productId: z.string(),
        shopId: z.string(),
        platform: z.string(),
        productData: z.object({
          externalId: z.string(),
          title: z.string(),
          description: z.string(),
          price: z.number(),
          currency: z.string(),
          images: z.array(z.string()),
          skus: z.array(z.any())
        })
      });

      const { productId, shopId, platform, productData } = schema.parse(req.body);
      const { tenantId, traceId } = (req as any).traceContext;

      const taskId = await PublishService.submitPublishTask({
        tenantId,
        shopId,
        productId,
        platform,
        productData,
        traceId
      });

      res.json({
        success: true,
        data: { taskId }
      });
    } catch (err: any) {
      if (err instanceof z.ZodError) {
        return res.status(400).json({ success: false, error: err.issues[0].message });
      }
      next(err);
    }
  }

  /**
   * [CORE_NODE_03] 接收 Node Agent 的执行回执
   */
  static async reportReceipt(req: Request, res: Response, next: NextFunction) {
    try {
      const receipt = req.body;
      await PublishService.handleNodeReceipt(receipt);
      res.json({ success: true });
    } catch (err: any) {
      next(err);
    }
  }
}
