import { Injectable, Logger } from '@nestjs/common';
import { db } from '../../config/database';

interface SkuData {
  id: string;
  productId: string;
  sku: string;
  price: number;
  stock: number;
  status: string;
  createdAt: Date;
  updatedAt: Date;
}

interface ProductData {
  id: string;
  tenantId: string;
  name: string;
  status: string;
  createdAt: Date;
  updatedAt: Date;
}

interface ReturnOptimizationResult {
  productId: string;
  productName: string;
  currentReturnRate: number;
  optimizedReturnRate: number;
  improvement: number;
  recommendations: string[];
  estimatedSavings: number;
}

interface OptimizationStrategy {
  productId: string;
  strategy: 'IMPROVE_QUALITY' | 'UPDATE_DESCRIPTION' | 'ADJUST_PRICING' | 'BUNDLE_OFFER';
  priority: 'high' | 'medium' | 'low';
  expectedImprovement: number;
  implementationCost: number;
  roi: number;
}

/**
 * [BE-RET-002] 退货优化服务
 * 负责退货率优化策略制定、效果预测、成本效益分析
 * AI注意: 所有退货优化操作必须通过此服务进行
 */
@Injectable()
export class ReturnOptimizationService {
  private readonly logger = new Logger(ReturnOptimizationService.name);

  constructor() {}

  /**
   * 优化退货率
   * @param tenantId 租户ID
   * @param productId 产品ID
   * @param traceId 链路追踪ID
   * @returns 退货优化结果
   */
  async optimizeReturnRate(
    tenantId: string,
    productId: string,
    traceId: string
  ): Promise<ReturnOptimizationResult> {
    this.logger.log(`开始优化退货率: ${tenantId}, ${productId}`, { traceId, tenantId, productId });

    try {
      const product = await db('cf_product')
        .where('id', productId)
        .first();

      if (!product) {
        throw new Error(`产品不存在: ${productId}`);
      }

      const currentReturnRate = await this.calculateReturnRate(tenantId, productId);
      const strategies = await this.generateOptimizationStrategies(tenantId, productId, currentReturnRate);
      const optimizedReturnRate = this.calculateOptimizedReturnRate(currentReturnRate, strategies);
      const recommendations = this.generateRecommendations(strategies);
      const estimatedSavings = await this.calculateEstimatedSavings(tenantId, productId, currentReturnRate, optimizedReturnRate);

      const result: ReturnOptimizationResult = {
        productId,
        productName: product.name,
        currentReturnRate,
        optimizedReturnRate,
        improvement: currentReturnRate - optimizedReturnRate,
        recommendations,
        estimatedSavings,
      };

      this.logger.log(`退货率优化完成: ${tenantId}, ${productId}`, { traceId, result });

      return result;
    } catch (error: unknown) {
      const errorMessage = error instanceof Error ? error.message : String(error);
      this.logger.error(`退货率优化失败: ${errorMessage}`, { traceId, tenantId, productId, error });
      throw error;
    }
  }

  /**
   * 批量优化退货率
   * @param tenantId 租户ID
   * @param productIds 产品ID列表
   * @param traceId 链路追踪ID
   * @returns 退货优化结果列表
   */
  async batchOptimizeReturnRates(
    tenantId: string,
    productIds: string[],
    traceId: string
  ): Promise<ReturnOptimizationResult[]> {
    this.logger.log(`开始批量优化退货率: ${tenantId}, 数量: ${productIds.length}`, { traceId });

    const results: ReturnOptimizationResult[] = [];

    for (const productId of productIds) {
      try {
        const result = await this.optimizeReturnRate(tenantId, productId, traceId);
        results.push(result);
      } catch (error) {
        this.logger.error(`批量优化退货率失败: ${productId}`, { traceId, productId });
      }
    }

    this.logger.log(`批量优化退货率完成, 成功: ${results.length}/${productIds.length}`, { traceId });

    return results;
  }

  /**
   * 计算退货率
   */
  private async calculateReturnRate(tenantId: string, productId: string): Promise<number> {
    const orderCount = await db('cf_order')
      .where('tenant_id', tenantId)
      .where('product_id', productId)
      .count('* as count');

    const returnCount = await db('cf_return')
      .where('tenant_id', tenantId)
      .where('product_id', productId)
      .count('* as count');

    const orderCountResult = orderCount[0] as any;
    const returnCountResult = returnCount[0] as any;
    const totalOrders = orderCountResult?.count || 0;
    const totalReturns = returnCountResult?.count || 0;

    if (totalOrders === 0) return 0;

    return (totalReturns / totalOrders) * 100;
  }

  /**
   * 生成优化策略
   */
  private async generateOptimizationStrategies(
    tenantId: string,
    productId: string,
    currentReturnRate: number
  ): Promise<OptimizationStrategy[]> {
    const strategies: OptimizationStrategy[] = [];

    const returns = await db('cf_return')
      .where('tenant_id', tenantId)
      .where('product_id', productId)
      .select('*');

    if (returns.length === 0) return strategies;

    const reasonCounts = new Map<string, number>();
    returns.forEach(r => {
      const reason = r.reason || 'unknown';
      reasonCounts.set(reason, (reasonCounts.get(reason) || 0) + 1);
    });

    const topReason = Array.from(reasonCounts.entries())
      .sort((a, b) => b[1] - a[1])[0];

    if (!topReason) return strategies;

    const [reason, count] = topReason;
    const percentage = (count / returns.length) * 100;

    if (percentage > 30) {
      strategies.push({
        productId,
        strategy: 'IMPROVE_QUALITY',
        priority: 'high',
        expectedImprovement: percentage * 0.6,
        implementationCost: 1000,
        roi: percentage * 0.6 * 100,
      });
    }

    if (reason.includes('description') || reason.includes('not as expected')) {
      strategies.push({
        productId,
        strategy: 'UPDATE_DESCRIPTION',
        priority: 'medium',
        expectedImprovement: percentage * 0.4,
        implementationCost: 200,
        roi: percentage * 0.4 * 100,
      });
    }

    if (reason.includes('price') || reason.includes('expensive')) {
      strategies.push({
        productId,
        strategy: 'ADJUST_PRICING',
        priority: 'medium',
        expectedImprovement: percentage * 0.3,
        implementationCost: 0,
        roi: percentage * 0.3 * 100,
      });
    }

    strategies.push({
      productId,
      strategy: 'BUNDLE_OFFER',
      priority: 'low',
      expectedImprovement: percentage * 0.2,
      implementationCost: 500,
      roi: percentage * 0.2 * 100,
    });

    return strategies.sort((a, b) => b.roi - a.roi);
  }

  /**
   * 计算优化后的退货率
   */
  private calculateOptimizedReturnRate(
    currentReturnRate: number,
    strategies: OptimizationStrategy[]
  ): number {
    const totalImprovement = strategies.reduce((sum, s) => sum + s.expectedImprovement, 0);
    const optimizedRate = Math.max(0, currentReturnRate - totalImprovement);
    return Math.round(optimizedRate * 100) / 100;
  }

  /**
   * 生成建议
   */
  private generateRecommendations(strategies: OptimizationStrategy[]): string[] {
    const recommendations: string[] = [];

    strategies.forEach(s => {
      switch (s.strategy) {
        case 'IMPROVE_QUALITY':
          recommendations.push('建议加强产品质量控制，减少质量相关退货');
          break;
        case 'UPDATE_DESCRIPTION':
          recommendations.push('建议优化产品描述和图片，确保与实物一致');
          break;
        case 'ADJUST_PRICING':
          recommendations.push('建议调整产品定价，提高性价比');
          break;
        case 'BUNDLE_OFFER':
          recommendations.push('建议推出组合优惠，提升产品价值');
          break;
      }
    });

    return recommendations;
  }

  /**
   * 计算预计节省
   */
  private async calculateEstimatedSavings(
    tenantId: string,
    productId: string,
    currentReturnRate: number,
    optimizedReturnRate: number
  ): Promise<number> {
    const orders = await db('cf_order')
      .where('tenant_id', tenantId)
      .where('product_id', productId)
      .select('*');

    if (orders.length === 0) return 0;

    const avgOrderValue = orders.reduce((sum, o) => sum + (o.total_amount || 0), 0) / orders.length;
    const monthlyOrders = orders.length / 12;
    const returnReduction = (currentReturnRate - optimizedReturnRate) / 100;
    const monthlySavings = monthlyOrders * avgOrderValue * returnReduction;

    return Math.round(monthlySavings * 12);
  }
}
