import currencyConversionService from './CurrencyConversionService';
import currencyService from './CurrencyService';
import { logger } from '../utils/logger';

export interface PriceCalculationParams {
  costPrice: number;
  costCurrency: string;
  markupPercentage: number;
  targetCurrency: string;
  additionalCosts?: number;
  additionalCostCurrency?: string;
}

export interface ProfitCalculationParams {
  sellingPrice: number;
  sellingCurrency: string;
  costPrice: number;
  costCurrency: string;
  additionalCosts?: number;
  additionalCostCurrency?: string;
}

export interface CurrencyCalculationService {
  calculatePrice(params: PriceCalculationParams): Promise<number>;
  calculateProfit(params: ProfitCalculationParams): Promise<number>;
  calculateProfitPercentage(params: ProfitCalculationParams): Promise<number>;
  calculateBreakEvenPrice(costPrice: number, costCurrency: string, targetCurrency: string, additionalCosts?: number, additionalCostCurrency?: string): Promise<number>;
  calculateMarkupPercentage(sellingPrice: number, sellingCurrency: string, costPrice: number, costCurrency: string, additionalCosts?: number, additionalCostCurrency?: string): Promise<number>;
}

export class CurrencyCalculationServiceImpl implements CurrencyCalculationService {
  async calculatePrice(params: PriceCalculationParams): Promise<number> {
    try {
      const { costPrice, costCurrency, markupPercentage, targetCurrency, additionalCosts = 0, additionalCostCurrency = costCurrency } = params;

      // 验证参数
      if (costPrice < 0) {
        throw new Error('Cost price cannot be negative');
      }
      if (markupPercentage < 0) {
        throw new Error('Markup percentage cannot be negative');
      }

      // 转换额外成本到成本货币
      let totalCost = costPrice;
      if (additionalCosts > 0 && additionalCostCurrency !== costCurrency) {
        const convertedAdditionalCosts = await currencyConversionService.convert(
          additionalCosts,
          additionalCostCurrency,
          costCurrency
        );
        totalCost += convertedAdditionalCosts;
      } else if (additionalCosts > 0) {
        totalCost += additionalCosts;
      }

      // 计算加价后的价格
      const markedUpPrice = totalCost * (1 + markupPercentage / 100);

      // 转换到目标货币
      const finalPrice = await currencyConversionService.convert(markedUpPrice, costCurrency, targetCurrency);

      logger.info(`[CurrencyCalculationService] Calculated price: ${finalPrice} ${targetCurrency} (cost: ${costPrice} ${costCurrency}, markup: ${markupPercentage}%)`);
      return finalPrice;
    } catch (error) {
      logger.error('[CurrencyCalculationService] Error calculating price:', error);
      throw new Error('Failed to calculate price');
    }
  }

  async calculateProfit(params: ProfitCalculationParams): Promise<number> {
    try {
      const { sellingPrice, sellingCurrency, costPrice, costCurrency, additionalCosts = 0, additionalCostCurrency = costCurrency } = params;

      // 验证参数
      if (sellingPrice < 0) {
        throw new Error('Selling price cannot be negative');
      }
      if (costPrice < 0) {
        throw new Error('Cost price cannot be negative');
      }

      // 转换所有成本到销售货币
      const convertedCostPrice = await currencyConversionService.convert(costPrice, costCurrency, sellingCurrency);
      
      let totalCost = convertedCostPrice;
      if (additionalCosts > 0 && additionalCostCurrency !== sellingCurrency) {
        const convertedAdditionalCosts = await currencyConversionService.convert(
          additionalCosts,
          additionalCostCurrency,
          sellingCurrency
        );
        totalCost += convertedAdditionalCosts;
      } else if (additionalCosts > 0) {
        totalCost += additionalCosts;
      }

      // 计算利润
      const profit = sellingPrice - totalCost;

      logger.info(`[CurrencyCalculationService] Calculated profit: ${profit} ${sellingCurrency} (selling: ${sellingPrice} ${sellingCurrency}, cost: ${costPrice} ${costCurrency})`);
      return profit;
    } catch (error) {
      logger.error('[CurrencyCalculationService] Error calculating profit:', error);
      throw new Error('Failed to calculate profit');
    }
  }

  async calculateProfitPercentage(params: ProfitCalculationParams): Promise<number> {
    try {
      const { sellingPrice, sellingCurrency, costPrice, costCurrency, additionalCosts = 0, additionalCostCurrency = costCurrency } = params;

      // 验证参数
      if (sellingPrice <= 0) {
        throw new Error('Selling price must be positive');
      }
      if (costPrice < 0) {
        throw new Error('Cost price cannot be negative');
      }

      // 转换所有成本到销售货币
      const convertedCostPrice = await currencyConversionService.convert(costPrice, costCurrency, sellingCurrency);
      
      let totalCost = convertedCostPrice;
      if (additionalCosts > 0 && additionalCostCurrency !== sellingCurrency) {
        const convertedAdditionalCosts = await currencyConversionService.convert(
          additionalCosts,
          additionalCostCurrency,
          sellingCurrency
        );
        totalCost += convertedAdditionalCosts;
      } else if (additionalCosts > 0) {
        totalCost += additionalCosts;
      }

      // 计算利润率
      const profit = sellingPrice - totalCost;
      const profitPercentage = (profit / totalCost) * 100;

      logger.info(`[CurrencyCalculationService] Calculated profit percentage: ${profitPercentage}% (selling: ${sellingPrice} ${sellingCurrency}, cost: ${costPrice} ${costCurrency})`);
      return profitPercentage;
    } catch (error) {
      logger.error('[CurrencyCalculationService] Error calculating profit percentage:', error);
      throw new Error('Failed to calculate profit percentage');
    }
  }

  async calculateBreakEvenPrice(costPrice: number, costCurrency: string, targetCurrency: string, additionalCosts: number = 0, additionalCostCurrency: string = costCurrency): Promise<number> {
    try {
      // 验证参数
      if (costPrice < 0) {
        throw new Error('Cost price cannot be negative');
      }

      // 转换额外成本到成本货币
      let totalCost = costPrice;
      if (additionalCosts > 0 && additionalCostCurrency !== costCurrency) {
        const convertedAdditionalCosts = await currencyConversionService.convert(
          additionalCosts,
          additionalCostCurrency,
          costCurrency
        );
        totalCost += convertedAdditionalCosts;
      } else if (additionalCosts > 0) {
        totalCost += additionalCosts;
      }

      // 转换到目标货币
      const breakEvenPrice = await currencyConversionService.convert(totalCost, costCurrency, targetCurrency);

      logger.info(`[CurrencyCalculationService] Calculated break-even price: ${breakEvenPrice} ${targetCurrency} (cost: ${costPrice} ${costCurrency})`);
      return breakEvenPrice;
    } catch (error) {
      logger.error('[CurrencyCalculationService] Error calculating break-even price:', error);
      throw new Error('Failed to calculate break-even price');
    }
  }

  async calculateMarkupPercentage(sellingPrice: number, sellingCurrency: string, costPrice: number, costCurrency: string, additionalCosts: number = 0, additionalCostCurrency: string = costCurrency): Promise<number> {
    try {
      // 验证参数
      if (sellingPrice <= 0) {
        throw new Error('Selling price must be positive');
      }
      if (costPrice < 0) {
        throw new Error('Cost price cannot be negative');
      }

      // 转换所有成本到销售货币
      const convertedCostPrice = await currencyConversionService.convert(costPrice, costCurrency, sellingCurrency);
      
      let totalCost = convertedCostPrice;
      if (additionalCosts > 0 && additionalCostCurrency !== sellingCurrency) {
        const convertedAdditionalCosts = await currencyConversionService.convert(
          additionalCosts,
          additionalCostCurrency,
          sellingCurrency
        );
        totalCost += convertedAdditionalCosts;
      } else if (additionalCosts > 0) {
        totalCost += additionalCosts;
      }

      // 计算加价百分比
      const markup = sellingPrice - totalCost;
      const markupPercentage = (markup / totalCost) * 100;

      logger.info(`[CurrencyCalculationService] Calculated markup percentage: ${markupPercentage}% (selling: ${sellingPrice} ${sellingCurrency}, cost: ${costPrice} ${costCurrency})`);
      return markupPercentage;
    } catch (error) {
      logger.error('[CurrencyCalculationService] Error calculating markup percentage:', error);
      throw new Error('Failed to calculate markup percentage');
    }
  }
}

export default new CurrencyCalculationServiceImpl();
