import { createProductAndPrices } from '../routes/products';
import { PaymentCurrency, PaymentMethod, Price, Product } from '../store/models';
import logger from './logger';

export const overdraftProtectionKey = 'overdraft-protection';

export async function ensureOverdraftProtectionPrice(livemode = true) {
  try {
    const lookUpKey = livemode ? overdraftProtectionKey : `${overdraftProtectionKey}-test`;
    const exist = await Price.findOne({ where: { lookup_key: lookUpKey, livemode } });
    if (exist) {
      const product = await Product.findByPk(exist.product_id);
      if (product?.name === 'Overdraft Protection') {
        product.update({ name: 'SubGuard Service' });
      }
      return {
        product,
        price: exist,
      };
    }
    const baseCurrency = await PaymentCurrency.findOne({ where: { is_base_currency: true, livemode } });
    const currencies = (await PaymentCurrency.findAll({
      where: { livemode },
      include: [{ model: PaymentMethod, as: 'payment_method' }],
    })) as (PaymentCurrency & { payment_method: PaymentMethod })[];

    const currencyOptions = currencies
      .filter((currency) => currency.payment_method?.type === 'arcblock')
      .map((currency) => ({ currency_id: currency.id, unit_amount: '1' }));

    const result = await createProductAndPrices({
      type: 'service',
      name: 'SubGuard Service',
      description:
        'If you purchase this service, the overdue subscription will be protected and not be ended due to overdue',
      images: [],
      statement_descriptor: '',
      unit_label: '',
      features: [],
      livemode,
      prices: [
        {
          livemode,
          locked: true,
          model: 'standard',
          billing_scheme: '',
          currency_id: baseCurrency?.id,
          nickname: '',
          type: 'one_time',
          unit_amount: '1',
          lookup_key: lookUpKey,
          recurring: {},
          transform_quantity: { divide_by: 1, round: 'up' },
          tiers: [],
          metadata: [],
          custom_unit_amount: null,
          currency_options: currencyOptions,
          tiers_mode: null,
          quantity_available: 0,
          quantity_limit_per_checkout: 0,
        },
      ],
      metadata: [],
    });
    logger.info('overdraft protection price created', {
      productId: result.id,
      priceId: result.prices?.[0]?.id,
    });
    return {
      product: result,
      price: result.prices?.[0],
    };
  } catch (err) {
    logger.error('create overdraft protection price error', err);
    return {
      product: null,
      price: null,
    };
  }
}

export async function ensureCreateOverdraftProtectionPrices() {
  try {
    await ensureOverdraftProtectionPrice(true);
    await ensureOverdraftProtectionPrice(false);
  } catch (err) {
    logger.error('ensure overdraft protection prices error', err);
  }
}
