import { DomainEventBus } from '../runtime/DomainEventBus';

// 策略信息
export interface Strategy {
  id: string;
  name: string;
  description: string;
  type: 'pricing' | 'product_selection' | 'marketing' | 'logistics' | 'risk';
  version: string;
  developerId: string;
  price: number;
  rating: number;
  usageCount: number;
  status: 'draft' | 'published' | 'archived';
  tags: string[];
  createdAt: Date;
  lastUpdated: Date;
  metadata?: Record<string, any>;
}

// 策略订阅
export interface StrategySubscription {
  id: string;
  strategyId: string;
  merchantId: string;
  status: 'active' | 'expired' | 'cancelled';
  startDate: Date;
  endDate: Date;
  price: number;
  metadata?: Record<string, any>;
}

// 策略评价
export interface StrategyReview {
  id: string;
  strategyId: string;
  merchantId: string;
  rating: number; // 1-5
  comment: string;
  createdAt: Date;
  metadata?: Record<string, any>;
}

// 策略市场
export class StrategyMarketplace {
  private static instance: StrategyMarketplace;
  private strategies: Map<string, Strategy> = new Map();
  private subscriptions: Map<string, StrategySubscription> = new Map();
  private reviews: Map<string, StrategyReview> = new Map();
  private eventBus: DomainEventBus;

  private constructor() {
    this.eventBus = DomainEventBus.getInstance();
  }

  static getInstance(): StrategyMarketplace {
    if (!StrategyMarketplace.instance) {
      StrategyMarketplace.instance = new StrategyMarketplace();
    }
    return StrategyMarketplace.instance;
  }

  // 发布策略
  async publishStrategy(strategy: Omit<Strategy, 'id' | 'rating' | 'usageCount' | 'status' | 'createdAt' | 'lastUpdated'>): Promise<Strategy> {
    const id = `strategy_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
    
    const newStrategy: Strategy = {
      ...strategy,
      id,
      rating: 0,
      usageCount: 0,
      status: 'published',
      createdAt: new Date(),
      lastUpdated: new Date()
    };

    this.strategies.set(id, newStrategy);
    this.eventBus.publish('strategy.published', newStrategy);
    return newStrategy;
  }

  // 获取策略信息
  getStrategy(strategyId: string): Strategy | undefined {
    return this.strategies.get(strategyId);
  }

  // 获取所有策略
  getAllStrategies(filters?: {
    type?: string;
    tags?: string[];
    minRating?: number;
    maxPrice?: number;
  }): Strategy[] {
    let result = Array.from(this.strategies.values());

    if (filters) {
      if (filters.type) {
        result = result.filter(s => s.type === filters.type);
      }

      if (filters.tags && filters.tags.length > 0) {
        result = result.filter(s => filters.tags!.some(tag => s.tags.includes(tag)));
      }

      if (filters.minRating !== undefined) {
        result = result.filter(s => s.rating >= filters.minRating!);
      }

      if (filters.maxPrice !== undefined) {
        result = result.filter(s => s.price <= filters.maxPrice!);
      }
    }

    return result;
  }

  // 获取开发者的策略
  getDeveloperStrategies(developerId: string): Strategy[] {
    return Array.from(this.strategies.values()).filter(s => s.developerId === developerId);
  }

  // 更新策略
  async updateStrategy(strategyId: string, updates: Partial<Strategy>): Promise<Strategy | null> {
    const strategy = this.strategies.get(strategyId);
    if (!strategy) {
      return null;
    }

    const updatedStrategy = {
      ...strategy,
      ...updates,
      lastUpdated: new Date()
    };

    this.strategies.set(strategyId, updatedStrategy);
    this.eventBus.publish('strategy.updated', updatedStrategy);
    return updatedStrategy;
  }

  // 归档策略
  async archiveStrategy(strategyId: string): Promise<boolean> {
    const strategy = this.strategies.get(strategyId);
    if (!strategy) {
      return false;
    }

    strategy.status = 'archived';
    strategy.lastUpdated = new Date();
    this.strategies.set(strategyId, strategy);
    this.eventBus.publish('strategy.archived', strategy);
    return true;
  }

  // 订阅策略
  async subscribeToStrategy(strategyId: string, merchantId: string, durationDays: number = 30): Promise<StrategySubscription> {
    const strategy = this.strategies.get(strategyId);
    if (!strategy || strategy.status !== 'published') {
      throw new Error('Strategy not available');
    }

    const id = `sub_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
    const startDate = new Date();
    const endDate = new Date();
    endDate.setDate(endDate.getDate() + durationDays);

    const subscription: StrategySubscription = {
      id,
      strategyId,
      merchantId,
      status: 'active',
      startDate,
      endDate,
      price: strategy.price * (durationDays / 30)
    };

    this.subscriptions.set(id, subscription);
    
    // 更新策略使用次数
    strategy.usageCount++;
    this.strategies.set(strategyId, strategy);

    this.eventBus.publish('strategy.subscribed', subscription);
    return subscription;
  }

  // 获取订阅信息
  getSubscription(subscriptionId: string): StrategySubscription | undefined {
    return this.subscriptions.get(subscriptionId);
  }

  // 获取商户的订阅
  getMerchantSubscriptions(merchantId: string): StrategySubscription[] {
    return Array.from(this.subscriptions.values()).filter(s => s.merchantId === merchantId);
  }

  // 获取策略的订阅
  getStrategySubscriptions(strategyId: string): StrategySubscription[] {
    return Array.from(this.subscriptions.values()).filter(s => s.strategyId === strategyId);
  }

  // 取消订阅
  async cancelSubscription(subscriptionId: string): Promise<boolean> {
    const subscription = this.subscriptions.get(subscriptionId);
    if (!subscription) {
      return false;
    }

    subscription.status = 'cancelled';
    this.subscriptions.set(subscriptionId, subscription);
    this.eventBus.publish('subscription.cancelled', subscription);
    return true;
  }

  // 评价策略
  async reviewStrategy(strategyId: string, merchantId: string, rating: number, comment: string): Promise<StrategyReview> {
    const strategy = this.strategies.get(strategyId);
    if (!strategy) {
      throw new Error('Strategy not found');
    }

    // 检查商户是否订阅过该策略
    const hasSubscription = Array.from(this.subscriptions.values()).some(
      s => s.strategyId === strategyId && s.merchantId === merchantId
    );

    if (!hasSubscription) {
      throw new Error('Merchant has not subscribed to this strategy');
    }

    const id = `review_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;

    const review: StrategyReview = {
      id,
      strategyId,
      merchantId,
      rating,
      comment,
      createdAt: new Date()
    };

    this.reviews.set(id, review);
    
    // 更新策略评分
    this.updateStrategyRating(strategyId);

    this.eventBus.publish('strategy.reviewed', review);
    return review;
  }

  // 获取策略的评价
  getStrategyReviews(strategyId: string): StrategyReview[] {
    return Array.from(this.reviews.values()).filter(r => r.strategyId === strategyId);
  }

  // 更新策略评分
  private updateStrategyRating(strategyId: string): void {
    const reviews = this.getStrategyReviews(strategyId);
    if (reviews.length === 0) {
      return;
    }

    const totalRating = reviews.reduce((sum, review) => sum + review.rating, 0);
    const averageRating = totalRating / reviews.length;

    const strategy = this.strategies.get(strategyId);
    if (strategy) {
      strategy.rating = averageRating;
      strategy.lastUpdated = new Date();
      this.strategies.set(strategyId, strategy);
    }
  }

  // 搜索策略
  searchStrategies(query: string, filters?: {
    type?: string;
    minRating?: number;
    maxPrice?: number;
  }): Strategy[] {
    let result = Array.from(this.strategies.values());

    // 关键词搜索
    if (query) {
      const lowerQuery = query.toLowerCase();
      result = result.filter(s => 
        s.name.toLowerCase().includes(lowerQuery) ||
        s.description.toLowerCase().includes(lowerQuery) ||
        s.tags.some(tag => tag.toLowerCase().includes(lowerQuery))
      );
    }

    // 应用过滤器
    if (filters) {
      if (filters.type) {
        result = result.filter(s => s.type === filters.type);
      }

      if (filters.minRating !== undefined) {
        result = result.filter(s => s.rating >= filters.minRating!);
      }

      if (filters.maxPrice !== undefined) {
        result = result.filter(s => s.price <= filters.maxPrice!);
      }
    }

    return result;
  }

  // 获取热门策略
  getPopularStrategies(limit: number = 10): Strategy[] {
    return Array.from(this.strategies.values())
      .filter(s => s.status === 'published')
      .sort((a, b) => b.usageCount - a.usageCount)
      .slice(0, limit);
  }

  // 获取推荐策略
  getRecommendedStrategies(merchantId: string, limit: number = 5): Strategy[] {
    // 这里应该有推荐算法
    // 暂时返回热门策略
    return this.getPopularStrategies(limit);
  }
}
