// Dynamic Pricing Service
// Calculates pricing based on usage profile and market conditions

import prisma from '@/shared/database/prisma';
import { logger } from '@/infrastructure/monitoring/logger';

export interface UsageProfile {
  estimatedVolume: number; // Transactions per month
  estimatedValue: number; // Total value in USD
  peakLoad: number; // Peak transactions per second
  dataVolume: number; // Data volume in GB
  regions: string[]; // Geographic regions
  features: string[]; // Required features
}

export interface PricingCalculation {
  basePrice: number;
  usageBasedPrice: number;
  featurePrice: number;
  regionalPrice: number;
  totalPrice: number;
  currency: string;
  breakdown: Array<{
    component: string;
    amount: number;
    description: string;
  }>;
  discount?: {
    percentage: number;
    amount: number;
    reason: string;
  };
}

export class DynamicPricingService {
  /**
   * Calculate pricing based on usage profile
   */
  async calculatePricing(
    offeringId: string,
    usageProfile: UsageProfile
  ): Promise<PricingCalculation> {
    const offering = await prisma.iruOffering.findUnique({
      where: { offeringId },
    });

    if (!offering) {
      throw new Error(`Offering ${offeringId} not found`);
    }

    const basePrice = offering.basePrice ? Number(offering.basePrice) : 0;
    const currency = offering.currency || 'USD';

    // Calculate usage-based pricing
    const usageBasedPrice = this.calculateUsageBasedPrice(usageProfile, basePrice);

    // Calculate feature-based pricing
    const featurePrice = this.calculateFeaturePrice(usageProfile.features, basePrice);

    // Calculate regional pricing
    const regionalPrice = this.calculateRegionalPrice(usageProfile.regions, basePrice);

    // Calculate total
    const totalPrice = basePrice + usageBasedPrice + featurePrice + regionalPrice;

    // Apply discounts
    const discount = this.calculateDiscount(usageProfile, totalPrice);

    const finalPrice = discount ? totalPrice - discount.amount : totalPrice;

    const breakdown = [
      {
        component: 'Base Price',
        amount: basePrice,
        description: 'Base IRU subscription fee',
      },
      {
        component: 'Usage-Based',
        amount: usageBasedPrice,
        description: `Based on ${usageProfile.estimatedVolume.toLocaleString()} transactions/month`,
      },
      {
        component: 'Features',
        amount: featurePrice,
        description: `${usageProfile.features.length} additional features`,
      },
      {
        component: 'Regional',
        amount: regionalPrice,
        description: `${usageProfile.regions.length} regions`,
      },
    ];

    if (discount) {
      breakdown.push({
        component: 'Discount',
        amount: -discount.amount,
        description: discount.reason,
      });
    }

    return {
      basePrice,
      usageBasedPrice,
      featurePrice,
      regionalPrice,
      totalPrice: finalPrice,
      currency,
      breakdown,
      discount,
    };
  }

  /**
   * Calculate usage-based price
   */
  private calculateUsageBasedPrice(usageProfile: UsageProfile, basePrice: number): number {
    // Tiered pricing based on volume
    const volume = usageProfile.estimatedVolume;
    let price = 0;

    if (volume > 1000000) {
      // > 1M transactions/month
      price = basePrice * 0.5; // 50% of base price
    } else if (volume > 500000) {
      // 500K - 1M transactions/month
      price = basePrice * 0.3;
    } else if (volume > 100000) {
      // 100K - 500K transactions/month
      price = basePrice * 0.15;
    } else if (volume > 10000) {
      // 10K - 100K transactions/month
      price = basePrice * 0.05;
    }

    // Add peak load surcharge
    if (usageProfile.peakLoad > 1000) {
      price += basePrice * 0.1; // 10% surcharge for high peak load
    }

    return price;
  }

  /**
   * Calculate feature-based price
   */
  private calculateFeaturePrice(features: string[], basePrice: number): number {
    // Standard features included in base price
    const standardFeatures = ['core_settlement', 'basic_reporting', 'standard_support'];
    const additionalFeatures = features.filter((f) => !standardFeatures.includes(f));

    // Each additional feature adds 5% of base price
    return (additionalFeatures.length * 0.05) * basePrice;
  }

  /**
   * Calculate regional price
   */
  private calculateRegionalPrice(regions: string[], basePrice: number): number {
    // First region included in base price
    if (regions.length <= 1) {
      return 0;
    }

    // Each additional region adds 10% of base price
    return ((regions.length - 1) * 0.1) * basePrice;
  }

  /**
   * Calculate discount
   */
  private calculateDiscount(usageProfile: UsageProfile, totalPrice: number): {
    percentage: number;
    amount: number;
    reason: string;
  } | undefined {
    // Volume discount
    if (usageProfile.estimatedVolume > 5000000) {
      return {
        percentage: 15,
        amount: totalPrice * 0.15,
        reason: 'High volume discount (15%)',
      };
    }

    if (usageProfile.estimatedVolume > 1000000) {
      return {
        percentage: 10,
        amount: totalPrice * 0.1,
        reason: 'Volume discount (10%)',
      };
    }

    // Multi-region discount
    if (usageProfile.regions.length > 3) {
      return {
        percentage: 5,
        amount: totalPrice * 0.05,
        reason: 'Multi-region discount (5%)',
      };
    }

    return undefined;
  }
}

export const dynamicPricingService = new DynamicPricingService();
