import { Request, Response, NextFunction } from 'express';
import { z } from 'zod';
import { EarlyStageBizService } from '../../core/biz/EarlyStageBizService';
import { OnboardingService } from '../../core/biz/OnboardingService';
import { TOCService } from '../../core/biz/TOCService';
import { FeatureGovernanceService } from '../../core/governance/FeatureGovernanceService';
import { logger } from '../../utils/logger';

/**
 * [BIZ_START_01] 前期业务控制器 (Early Stage Business Controller)
 * @description 处理新手引导、极速刊登、店铺初始化等“冷启动”业务。
 */
export class BizController {
  /**
   * [BIZ_TOC_01] 启动商品本地化 (ToC 增强)
   */
  static async startLocalization(req: Request, res: Response, next: NextFunction) {
    try {
      const bodySchema = z.object({
        productId: z.string(),
        targetLanguages: z.array(z.string()),
        optimizeImages: z.boolean().default(true)
      });

      const params = bodySchema.parse(req.body);
      const { tenantId } = (req as any).traceContext;

      await TOCService.startLocalization({
        ...params,
        tenantId
      });

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

  /**
   * [UX_START_01] 获取新手引导步骤
   */
  static async getOnboarding(req: Request, res: Response, next: NextFunction) {
    try {
      const { tenantId } = (req as any).traceContext;

      if (!(await FeatureGovernanceService.isEnabled('BIZ_START_ONBOARDING', tenantId))) {
        return res.status(403).json({ success: false, error: 'Onboarding feature is disabled for this tenant' });
      }

      const steps = await OnboardingService.getOnboardingSteps(tenantId);
      res.json({ success: true, data: steps });
    } catch (err: any) {
      next(err);
    }
  }

  /**
   * [BIZ_START_01_EXT] 一键店铺初始化
   */
  static async setupStore(req: Request, res: Response, next: NextFunction) {
    try {
      const { tenantId } = (req as any).traceContext;

      if (!(await FeatureGovernanceService.isEnabled('BIZ_START_ONE_CLICK_SETUP', tenantId))) {
        return res.status(403).json({ success: false, error: 'One-click setup is disabled' });
      }

      const bodySchema = z.object({
        platform: z.enum(['SHOPIFY', 'TIKTOK', 'AMAZON']),
        apiKey: z.string(),
        storeName: z.string()
      });

      const params = bodySchema.parse(req.body);

      const authId = await EarlyStageBizService.setupStore({
        ...params,
        tenantId
      });

      // 自动更新新手任务状态
      await OnboardingService.updateStepStatus(tenantId, 'AUTH_STORE', 'COMPLETED');

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

  /**
   * [BIZ_START_02_EXT] 极速刊登
   */
  static async quickListing(req: Request, res: Response, next: NextFunction) {
    try {
      const { tenantId } = (req as any).traceContext;

      if (!(await FeatureGovernanceService.isEnabled('BIZ_START_QUICK_LIST', tenantId))) {
        return res.status(403).json({ success: false, error: 'Quick listing is disabled' });
      }

      const bodySchema = z.object({
        sourceUrl: z.string().url(),
        targetPlatforms: z.array(z.string()),
        optimizeWithAI: z.boolean().default(true)
      });

      const params = bodySchema.parse(req.body);

      const productIds = await EarlyStageBizService.quickListing({
        ...params,
        tenantId
      });

      // 自动更新新手任务状态
      await OnboardingService.updateStepStatus(tenantId, 'QUICK_LIST', 'COMPLETED');

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

  /**
   * [BIZ_START_02_EXT] 极速选品雷达
   */
  static async getSourcingRadar(req: Request, res: Response, next: NextFunction) {
    try {
      const { tenantId } = (req as any).traceContext;
      const { category } = req.query;

      if (!(await FeatureGovernanceService.isEnabled('BIZ_START_QUICK_LIST', tenantId))) {
        return res.status(403).json({ success: false, error: 'Sourcing radar is disabled' });
      }

      const results = await EarlyStageBizService.getFastSourcingRadar(tenantId, category as string || 'General');
      res.json({ success: true, data: results });
    } catch (err: any) {
      next(err);
    }
  }
}
