import { fromTokenToUnit, fromUnitToToken } from '@ocap/util';
import { getUrl } from '@blocklet/sdk';
import { PaymentCurrency, Price, Product, RechargeConfig } from '../store/models';
import { trimDecimals } from './math-utils';
import { createPaymentLink } from '../routes/payment-links';
import logger from './logger';

export async function formatCurrencyToken(amount: string, currencyId: string) {
  if (!amount) {
    return '0';
  }
  if (!currencyId) {
    return amount;
  }
  const currency = await PaymentCurrency.findByPk(currencyId);
  if (!currency) {
    throw new Error(`Currency ${currencyId} not found`);
  }
  return fromUnitToToken(trimDecimals(amount || '0', currency.decimal), currency.decimal);
}

export async function formatCurrencyUnit(amount: string, currencyId: string) {
  if (!amount) {
    return '0';
  }
  if (!currencyId) {
    return amount;
  }
  const currency = await PaymentCurrency.findByPk(currencyId);
  if (!currency) {
    throw new Error(`Currency ${currencyId} not found`);
  }
  return fromTokenToUnit(amount || '0', currency.decimal).toString();
}

export async function getRechargePaymentUrl(
  currency: PaymentCurrency & { recharge_config?: RechargeConfig }
): Promise<string | null> {
  try {
    if (!currency || !currency.recharge_config) {
      return null;
    }

    const rechargeConfig = currency.recharge_config;
    const checkoutUrl = rechargeConfig.checkout_url;

    if (checkoutUrl) {
      return checkoutUrl;
    }

    if (rechargeConfig.payment_link_id) {
      return getUrl(`/checkout/pay/${rechargeConfig.payment_link_id}`);
    }

    if (rechargeConfig.base_price_id) {
      const basePrice = (await Price.findByPk(rechargeConfig.base_price_id, {
        include: [{ model: Product, as: 'product' }],
      })) as (Price & { product: Product }) | null;

      if (!basePrice) {
        logger.warn('Base price not found for recharge config', {
          currencyId: currency.id,
          basePriceId: rechargeConfig.base_price_id,
        });
        return null;
      }

      const paymentLink = await createPaymentLink({
        livemode: currency.livemode,
        currency_id: basePrice.currency_id,
        name: basePrice.product?.name || `${currency.name} Recharge`,
        submit_type: 'pay',
        allow_promotion_codes: true,
        line_items: [
          {
            price_id: rechargeConfig.base_price_id,
            quantity: 1,
            adjustable_quantity: {
              enabled: true,
              minimum: 1,
              maximum: 100000000,
            },
          },
        ],
      });

      await currency.update({
        recharge_config: { ...rechargeConfig, payment_link_id: paymentLink.id },
      });

      return getUrl(`/checkout/pay/${paymentLink.id}`);
    }

    return null;
  } catch (error: any) {
    logger.error('Failed to get recharge payment URL', {
      currencyId: currency.id,
      error: error.message,
    });
    return null;
  }
}
