import { getPricingConfig } from '../config.js';

export function readPricingConfig() {
  return getPricingConfig();
}

function normalizePackageIdFromConfig(packageId, pricingConfig) {
  // If the ID matches a canonical package ID, return it directly
  if ((pricingConfig.packages || []).some(p => p.id === packageId)) return packageId;
  // Otherwise, search for the ID in any package's aliases array
  const pkg = (pricingConfig.packages || []).find(p => (p.aliases || []).includes(packageId));
  return pkg ? pkg.id : packageId;
}

export function normalizePackageId(packageId) {
  return normalizePackageIdFromConfig(packageId, readPricingConfig());
}

export function getPackageSize(packageId) {
  const config = readPricingConfig();
  const canonicalPackageId = normalizePackageIdFromConfig(packageId, config);
  return (config.packages || []).find(pkg => pkg.id === canonicalPackageId)?.size;
}

function roundMoney(value) {
  return Math.round((Number(value) + Number.EPSILON) * 100) / 100;
}

function ceilMoney(value) {
  return Math.ceil((Number(value) - Number.EPSILON) * 100) / 100;
}

export function formatAmount(amount) {
  return Number.isInteger(amount) ? String(amount) : amount.toFixed(2).replace(/0+$/, '').replace(/\.$/, '');
}

function getPackageDiscountPercent(pkg, pricing) {
  return Number(pkg.discountPercent ?? pricing.discountPercent ?? 0);
}

function getPackageProfitPercent(pkg, pricing) {
  return Number(pkg.profitPercent ?? pricing.profitPercent ?? 0);
}

export function computePackagePrices(pkg, pricingConfig = readPricingConfig()) {
  let normalCost = pkg.normal?.cost ?? pkg.usd;
  
  // If it's a dynamic combo, calculate normalCost from its components
  if (pkg.composition && Array.isArray(pkg.composition)) {
    normalCost = 0;
    for (const compId of pkg.composition) {
      // Find the base package. In a combo, the components use their normal (PIN) cost.
      const basePkg = (pricingConfig.packages || []).find(p => p.id === compId);
      if (basePkg) {
        normalCost += Number(basePkg.normal?.cost ?? basePkg.usd ?? 0);
      }
    }
  }

  const normalProfit = pkg.normal?.profit ?? pkg.profitPercent ?? 0;
  
  if (!Number.isFinite(normalCost) || normalCost <= 0) return null;
  if (!Number.isFinite(normalProfit) || normalProfit < 0) return null;

  const normalNet = roundMoney(normalCost * (1 + normalProfit / 100));
  let discountedNet = normalNet; // Combos default to normal price

  if (pkg.promo) {
    const promoCost = pkg.promo.cost;
    const promoProfit = pkg.promo.profit ?? 0;
    if (Number.isFinite(promoCost) && promoCost > 0 && Number.isFinite(promoProfit) && promoProfit >= 0) {
      discountedNet = roundMoney(promoCost * (1 + promoProfit / 100));
    }
  }

  const usdtNormal = normalNet;
  const usdt = discountedNet;

  if (![usdtNormal, usdt].every(v => Number.isFinite(v) && v > 0)) return null;

  return {
    id: pkg.id,
    size: pkg.size,
    usd: normalCost, // dynamic cost if combo
    usdt,
    usdtNormal,
    discountPercent: 30,
  };
}

export function getComputedPackages() {
  const config = readPricingConfig();
  return (config.packages || []).map(pkg => computePackagePrices(pkg, config)).filter(Boolean);
}

export function resolvePaymentPricing(paymentMethod = '') {
  const method = String(paymentMethod).toLowerCase();
  if (
    method.includes('pm-crypto') ||
    method.includes('pm-binance') ||
    method.includes('crypto') ||
    method.includes('billetera') ||
    method.includes('binance') ||
    method.includes('usdt') ||
    method.includes('usdc')
  ) {
    return { discountedField: 'usdt', normalField: 'usdtNormal', currency: 'USD' };
  }
  if (method.includes('pm-transfer') || method.includes('transferencia') || method.includes('transfer')) {
    return { discountedField: 'usdt', normalField: 'usdtNormal', currency: 'USD' };
  }
  return null;
}

export function computeOrderPrice({ packageId, paymentMethod, isDiscounted }) {
  const config = readPricingConfig();
  const canonicalPackageId = normalizePackageIdFromConfig(packageId, config);
  const rawPackage = (config.packages || []).find(p => p.id === canonicalPackageId);
  if (!rawPackage) return { error: 'invalid_package' };

  const pkg = computePackagePrices(rawPackage, config);
  if (!pkg) return { error: 'invalid_price_config' };

  const pricing = resolvePaymentPricing(paymentMethod);
  if (!pricing) return { error: 'invalid_payment_method' };

  const priceField = isDiscounted ? pricing.discountedField : pricing.normalField;
  const expectedAmount = Number(pkg[priceField]);
  if (!Number.isFinite(expectedAmount) || expectedAmount <= 0) return { error: 'invalid_price_config' };

  return {
    packageId: rawPackage.id,
    packageSize: pkg.size,
    expectedAmount,
    expectedCurrency: pricing.currency,
    priceField,
    priceSource: `backend/config.js:${rawPackage.id}:usd:${priceField}`,
    priceInfo: `${formatAmount(expectedAmount)} ${pricing.currency}`,
    discountPercent: pkg.discountPercent,
    profitPercent: pkg.profitPercent,
    baseUsd: pkg.usd,
  };
}

/** Paquete de Aumento de Nivel: precio FIJO desde config.json (sin bonos). */
export function findLevelPackage(id) {
  const cfg = readPricingConfig();
  return (cfg.levelPackages || []).find((p) => p.id === id) || null;
}

export function computeLevelOrderItem(id) {
  const lp = findLevelPackage(id);
  if (!lp) return { error: 'invalid_package' };
  return {
    packageId: lp.id,
    kind: 'level',
    level: lp.level,
    packageSize: lp.diamonds,
    expectedAmount: roundMoney(Number(lp.usd)),
    expectedCurrency: 'USD',
    priceInfo: `${formatAmount(roundMoney(Number(lp.usd)))} USD`,
    priceSource: `config.json:levelPackages:${lp.id}`,
    isDiscounted: false,
    bonusUsed: false,
  };
}