import { Router, Request, Response, NextFunction } from 'express';
import { OperationAgentController } from '../controllers/OperationAgentController';
import { Container } from 'typedi';
import { z } from 'zod';

// 验证模式
const bindStoreSchema = z.object({
  merchantId: z.string().min(1, 'Merchant ID is required'),
  platform: z.string().min(1, 'Platform is required'),
  platformShopId: z.string().min(1, 'Platform shop ID is required'),
  name: z.string().min(1, 'Store name is required'),
  description: z.string().optional(),
  config: z.record(z.string(), z.any()).optional()
});

const updatePriceSchema = z.object({
  price: z.number().positive('Price must be positive')
});

const merchantIdSchema = z.string().min(1, 'Merchant ID is required');
const storeIdSchema = z.string().min(1, 'Store ID is required');
const productIdSchema = z.string().min(1, 'Product ID is required');

// 验证中间件
const validateBody = (schema: z.ZodObject<any>) => {
  return (req: Request, res: Response, next: NextFunction) => {
    try {
      schema.parse(req.body);
      next();
    } catch (error: unknown) {
      const errorMessage = error instanceof Error ? error.message : String(error);
      res.status(400).json({ error: errorMessage });
    }
  };
};

const validateParam = (paramName: string, schema: z.ZodString) => {
  return (req: Request, res: Response, next: NextFunction) => {
    try {
      schema.parse(req.params[paramName]);
      next();
    } catch (error: unknown) {
      const errorMessage = error instanceof Error ? error.message : String(error);
      res.status(400).json({ error: errorMessage });
    }
  };
};

const router = Router();
const operationAgentController = Container.get(OperationAgentController);

// 绑定店铺
router.post('/stores', validateBody(bindStoreSchema), (req, res, next) => {
  operationAgentController.bindStore(req.body)
    .then(result => res.json(result))
    .catch(next);
});

// 获取商户的店铺列表
router.get('/stores/:merchantId', validateParam('merchantId', merchantIdSchema), (req, res, next) => {
  operationAgentController.getStores(req.params.merchantId as string)
    .then(result => res.json(result))
    .catch(next);
});

// 获取店铺详情
router.get('/stores/detail/:storeId', validateParam('storeId', storeIdSchema), (req, res, next) => {
  operationAgentController.getStore(req.params.storeId as string)
    .then(result => res.json(result))
    .catch(next);
});

// 同步店铺商品
router.post('/stores/:storeId/products/sync', validateParam('storeId', storeIdSchema), (req, res, next) => {
  operationAgentController.syncProducts(req.params.storeId as string)
    .then(result => res.json(result))
    .catch(next);
});

// 同步店铺订单
router.post('/stores/:storeId/orders/sync', validateParam('storeId', storeIdSchema), (req, res, next) => {
  operationAgentController.syncOrders(req.params.storeId as string)
    .then(result => res.json(result))
    .catch(next);
});

// 更新商品价格
router.put('/stores/:storeId/products/:productId/price', 
  validateParam('storeId', storeIdSchema),
  validateParam('productId', productIdSchema),
  validateBody(updatePriceSchema),
  (req, res, next) => {
    operationAgentController.updateProductPrice(req.params.storeId as string, req.params.productId as string, req.body.price)
      .then(result => res.json(result))
      .catch(next);
  }
);

// 停用店铺
router.put('/stores/:storeId/deactivate', validateParam('storeId', storeIdSchema), (req, res, next) => {
  operationAgentController.deactivateStore(req.params.storeId as string)
    .then(result => res.json(result))
    .catch(next);
});

// 重新激活店铺
router.put('/stores/:storeId/reactivate', validateParam('storeId', storeIdSchema), (req, res, next) => {
  operationAgentController.reactivateStore(req.params.storeId as string)
    .then(result => res.json(result))
    .catch(next);
});

export default router;
