/* eslint-disable @typescript-eslint/brace-style */
/* eslint-disable @typescript-eslint/indent */
import { withQuery } from 'ufo';
import { getUserLocale } from '../../../integrations/blocklet/notification';
import { translate } from '../../../locales';
import { AutoRechargeConfig, Customer, PaymentMethod, Price, Product } from '../../../store/models';
import { PaymentCurrency } from '../../../store/models/payment-currency';
import { getRechargePaymentUrl } from '../../currency';
import { formatTime } from '../../time';
import { formatCurrencyInfo, getConnectQueryParam, getCustomerIndexUrl } from '../../util';
import type { BaseEmailTemplate, BaseEmailTemplateType } from './base';

export interface CustomerAutoRechargeDailyLimitExceededEmailTemplateOptions {
  customerId: string;
  autoRechargeConfigId: string;
  currencyId: string;
  currentBalance: string;
}

interface CustomerAutoRechargeDailyLimitExceededEmailTemplateContext {
  locale: string;
  userDid: string;
  at: string;
  creditCurrencyName: string;
  currentBalance: string;
  dailyLimit: string;
  dailyUsed: string;
  rechargeUrl: string | null;
  customerIndexUrl: string;
}

export class CustomerAutoRechargeDailyLimitExceededEmailTemplate implements BaseEmailTemplate<CustomerAutoRechargeDailyLimitExceededEmailTemplateContext> {
  options: CustomerAutoRechargeDailyLimitExceededEmailTemplateOptions;

  constructor(options: CustomerAutoRechargeDailyLimitExceededEmailTemplateOptions) {
    this.options = options;
  }

  async getContext(): Promise<CustomerAutoRechargeDailyLimitExceededEmailTemplateContext> {
    const customer = await Customer.findByPk(this.options.customerId);
    if (!customer) {
      throw new Error(`Customer not found: ${this.options.customerId}`);
    }

    const autoRechargeConfig = await AutoRechargeConfig.findByPk(this.options.autoRechargeConfigId, {
      include: [
        {
          model: Price,
          as: 'price',
          include: [{ model: Product, as: 'product' }],
        },
        {
          model: PaymentMethod,
          as: 'paymentMethod',
        },
        {
          model: PaymentCurrency,
          as: 'rechargeCurrency',
        },
      ],
    });
    if (!autoRechargeConfig) {
      throw new Error(`AutoRechargeConfig not found: ${this.options.autoRechargeConfigId}`);
    }

    // Get credit currency
    const creditCurrency = await PaymentCurrency.findByPk(autoRechargeConfig.currency_id);
    if (!creditCurrency) {
      throw new Error(`Credit currency not found: ${autoRechargeConfig.currency_id}`);
    }

    const rechargeCurrency = await PaymentCurrency.findByPk(autoRechargeConfig.recharge_currency_id);
    const paymentMethod = await PaymentMethod.findByPk(autoRechargeConfig.payment_method_id);

    const userDid: string = customer.did;
    const locale = await getUserLocale(userDid);
    const at: string = formatTime(Date.now());

    const creditCurrencyName = creditCurrency.name || 'Credits';
    const currentBalance = formatCurrencyInfo(this.options.currentBalance, creditCurrency, null);

    // Format daily limit and usage
    const dailyLimit = rechargeCurrency
      ? formatCurrencyInfo(autoRechargeConfig.daily_limits?.max_amount || '0', rechargeCurrency, paymentMethod)
      : autoRechargeConfig.daily_limits?.max_amount || '0';
    const dailyUsed = rechargeCurrency
      ? formatCurrencyInfo(autoRechargeConfig.daily_stats?.total_amount || '0', rechargeCurrency, paymentMethod)
      : autoRechargeConfig.daily_stats?.total_amount || '0';

    // Get recharge URL
    let rechargeUrl: string | null = await getRechargePaymentUrl(creditCurrency);
    if (rechargeUrl) {
      rechargeUrl = withQuery(rechargeUrl, { ...getConnectQueryParam({ userDid }) });
    }

    // Get customer index URL for managing credits
    const customerIndexUrl = getCustomerIndexUrl({
      locale,
      userDid,
    });

    return {
      locale,
      userDid,
      at,
      creditCurrencyName,
      currentBalance,
      dailyLimit,
      dailyUsed,
      rechargeUrl,
      customerIndexUrl,
    };
  }

  async getTemplate(): Promise<BaseEmailTemplateType> {
    const {
      locale,
      userDid,
      at,
      creditCurrencyName,
      currentBalance,
      dailyLimit,
      dailyUsed,
      rechargeUrl,
      customerIndexUrl,
    } = await this.getContext();

    const template: BaseEmailTemplateType = {
      title: translate('notification.autoRechargeDailyLimitExceeded.title', locale),
      body: translate('notification.autoRechargeDailyLimitExceeded.body', locale, {
        at,
        creditCurrencyName,
      }),
      // @ts-expect-error
      attachments: [
        {
          type: 'section',
          fields: [
            {
              type: 'text',
              data: {
                type: 'plain',
                color: '#9397A1',
                text: translate('notification.common.account', locale),
              },
            },
            {
              type: 'text',
              data: {
                type: 'plain',
                text: userDid,
              },
            },
            {
              type: 'text',
              data: {
                type: 'plain',
                color: '#9397A1',
                text: translate('notification.common.currentBalance', locale),
              },
            },
            {
              type: 'text',
              data: {
                type: 'plain',
                color: '#FF6B00',
                text: currentBalance,
              },
            },
            {
              type: 'text',
              data: {
                type: 'plain',
                color: '#9397A1',
                text: translate('notification.autoRechargeDailyLimitExceeded.dailyLimit', locale),
              },
            },
            {
              type: 'text',
              data: {
                type: 'plain',
                text: dailyLimit,
              },
            },
            {
              type: 'text',
              data: {
                type: 'plain',
                color: '#9397A1',
                text: translate('notification.autoRechargeDailyLimitExceeded.dailyUsed', locale),
              },
            },
            {
              type: 'text',
              data: {
                type: 'plain',
                text: dailyUsed,
              },
            },
          ].filter(Boolean),
        },
      ].filter(Boolean),
      // @ts-ignore
      actions: [
        rechargeUrl && {
          name: translate('notification.common.reloadCredits', locale),
          title: translate('notification.common.reloadCredits', locale),
          link: rechargeUrl,
        },
        {
          name: translate('notification.common.manageCredit', locale),
          title: translate('notification.common.manageCredit', locale),
          link: customerIndexUrl,
        },
      ].filter(Boolean),
    };

    return template;
  }
}
