/* eslint-disable @typescript-eslint/brace-style */
/* eslint-disable @typescript-eslint/indent */
import { translate } from '../../../locales';
import { PaymentIntent, PaymentMethod, Refund, Subscription } from '../../../store/models';
import { Invoice } from '../../../store/models/invoice';
import { PaymentCurrency } from '../../../store/models/payment-currency';
import { getCustomerInvoicePageUrl } from '../../invoice';
import { formatTime } from '../../time';
import { formatCurrencyInfo, getExplorerLink } from '../../util';
import { BaseSubscriptionEmailTemplate, BaseEmailTemplateType } from './base';

export interface SubscriptionRefundSucceededEmailTemplateOptions {
  refundId: string;
}

interface SubscriptionRefundSucceededEmailTemplateContext {
  locale: string;
  productName: string;
  at: string;
  chainHost: string | undefined;
  userDid: string;
  paymentInfo: string;
  refundInfo: string;
  currentPeriodStart?: string;
  currentPeriodEnd?: string;
  duration: string;
  unusedPeriodStart?: string;
  unusedPeriodEnd?: string;
  unusedDuration: string;
  viewSubscriptionLink: string;
  viewTxHashLink: string | undefined;
  viewInvoiceLink: string;
  refund: Refund;
  customActions: any[];
  isCreditSubscription: boolean;
}

export class SubscriptionRefundSucceededEmailTemplate extends BaseSubscriptionEmailTemplate<SubscriptionRefundSucceededEmailTemplateContext> {
  options: SubscriptionRefundSucceededEmailTemplateOptions;

  constructor(options: SubscriptionRefundSucceededEmailTemplateOptions) {
    super();
    this.options = options;
  }

  async getContext(): Promise<SubscriptionRefundSucceededEmailTemplateContext> {
    const refund = await Refund.findByPk(this.options.refundId);
    if (!refund) {
      throw new Error(`Refund not found: ${this.options.refundId}`);
    }
    if (refund.status !== 'succeeded') {
      throw new Error(`Refund not succeeded: ${this.options.refundId}`);
    }
    if (!refund.subscription_id) {
      throw new Error(`Refund must have subscription_id: ${this.options.refundId}`);
    }

    // 获取基础订阅数据
    const basicData = await this.getSubscriptionBasicData(refund.subscription_id);
    const { userDid, locale, productName, isCreditSubscription } = basicData;

    // 获取支付相关信息
    const paymentIntent = await PaymentIntent.findByPk(refund.payment_intent_id);
    const paymentCurrency = await PaymentCurrency.findByPk(refund.currency_id);
    if (!paymentCurrency) {
      throw new Error(`PaymentCurrency not found: ${refund.currency_id}`);
    }

    // 获取发票和周期信息
    let invoice = null;
    let currentPeriodStart;
    let currentPeriodEnd;
    let duration = '';
    let unusedPeriodStart;
    let unusedPeriodEnd;
    let unusedDuration = '';

    if (refund.type === 'refund') {
      invoice = await Invoice.findByPk(refund.invoice_id);
      if (invoice) {
        const periodInfo = this.formatSubscriptionPeriod(invoice.period_start, invoice.period_end, locale);
        currentPeriodStart = periodInfo.currentPeriodStart;
        currentPeriodEnd = periodInfo.currentPeriodEnd;
        duration = periodInfo.duration;

        // 处理未使用期间
        if (refund?.metadata?.unused_period_start && refund?.metadata?.unused_period_end) {
          const unusedPeriodInfo = this.formatSubscriptionPeriod(
            refund.metadata.unused_period_start,
            refund.metadata.unused_period_end,
            locale
          );
          unusedPeriodStart = unusedPeriodInfo.currentPeriodStart;
          unusedPeriodEnd = unusedPeriodInfo.currentPeriodEnd;
          unusedDuration = unusedPeriodInfo.duration;
        }
      }
    }

    // 获取支付方式
    const paymentMethod = await PaymentMethod.findByPk(refund.payment_method_id || invoice?.default_payment_method_id);

    // 格式化支付和退款信息
    const paymentInfo = formatCurrencyInfo(paymentIntent?.amount_received || '0', paymentCurrency, paymentMethod);
    const refundInfo = formatCurrencyInfo(refund.amount, paymentCurrency, paymentMethod);

    // 获取链接
    let customActions: any[] = [];
    let viewSubscriptionLink = '';

    if (refund?.subscription_id) {
      const subscription = await Subscription.findByPk(refund.subscription_id);
      if (subscription) {
        const links = this.generateSubscriptionLinks(
          subscription,
          locale,
          userDid,
          'refund.succeeded',
          undefined,
          isCreditSubscription
        );
        viewSubscriptionLink = links.viewSubscriptionLink;
        customActions = links.customActions;
      }
    }

    const viewInvoiceLink = refund.invoice_id
      ? getCustomerInvoicePageUrl({
          invoiceId: refund.invoice_id,
          locale,
          userDid,
        })
      : '';
    // 获取交易哈希链接
    // @ts-expect-error
    const chainHost = paymentMethod?.settings?.[paymentMethod?.type]?.api_host;
    // @ts-expect-error
    const txHash = refund?.payment_details?.[paymentMethod?.type]?.tx_hash;
    const viewTxHashLink =
      txHash &&
      getExplorerLink({
        type: 'tx',
        did: txHash,
        chainHost,
      });

    const at = formatTime(refund.created_at);

    return {
      locale,
      productName,
      at,
      userDid,
      chainHost,
      paymentInfo,
      refundInfo,
      currentPeriodStart,
      currentPeriodEnd,
      duration,
      unusedPeriodStart,
      unusedPeriodEnd,
      unusedDuration,
      viewSubscriptionLink,
      viewTxHashLink,
      refund,
      customActions,
      isCreditSubscription,
      viewInvoiceLink,
    };
  }

  async getTemplate(): Promise<BaseEmailTemplateType> {
    const context = await this.getContext();
    const {
      locale,
      productName,
      at,
      userDid,
      paymentInfo,
      refundInfo,
      currentPeriodStart,
      currentPeriodEnd,
      duration,
      unusedPeriodStart,
      unusedPeriodEnd,
      unusedDuration,
      viewSubscriptionLink,
      viewTxHashLink,
      refund,
      isCreditSubscription,
      viewInvoiceLink,
    } = context;

    // 如果是质押返还类型，使用特殊模板
    if (refund.type === 'stake_return') {
      return this.getStakeReturnTemplate(context);
    }

    // 构建字段
    const commonFields = this.buildCommonFields(userDid, productName, locale);

    // 支付和退款金额字段
    const amountFields = isCreditSubscription
      ? []
      : [
          {
            type: 'text',
            data: {
              type: 'plain',
              color: '#9397A1',
              text: translate('notification.common.paymentAmount', locale),
            },
          },
          {
            type: 'text',
            data: {
              type: 'plain',
              text: paymentInfo,
            },
          },
          {
            type: 'text',
            data: {
              type: 'plain',
              color: '#9397A1',
              text: translate('notification.common.refundAmount', locale),
            },
          },
          {
            type: 'text',
            data: {
              type: 'plain',
              text: refundInfo,
            },
          },
        ];

    // 有效期字段
    const validityPeriodFields =
      currentPeriodStart && currentPeriodEnd && !isCreditSubscription
        ? [
            {
              type: 'text',
              data: {
                type: 'plain',
                color: '#9397A1',
                text: translate('notification.common.validityPeriod', locale),
              },
            },
            {
              type: 'text',
              data: {
                type: 'plain',
                text: `${currentPeriodStart} ~ ${currentPeriodEnd}(${duration})`,
              },
            },
          ]
        : [];

    // 退款期间字段
    const refundPeriodFields =
      unusedPeriodStart && unusedPeriodEnd && unusedDuration && !isCreditSubscription
        ? [
            {
              type: 'text',
              data: {
                type: 'plain',
                color: '#9397A1',
                text: translate('notification.common.refundPeriod', locale),
              },
            },
            {
              type: 'text',
              data: {
                type: 'plain',
                text: `${unusedPeriodStart} ~ ${unusedPeriodEnd}(${unusedDuration})`,
              },
            },
          ]
        : [];

    // 构建操作按钮
    const actions = [
      viewSubscriptionLink && {
        name: translate('notification.common.viewSubscription', locale),
        title: translate('notification.common.viewSubscription', locale),
        link: viewSubscriptionLink,
      },
      viewInvoiceLink && {
        name: translate('notification.common.viewInvoice', locale),
        title: translate('notification.common.viewInvoice', locale),
        link: viewInvoiceLink,
      },
      viewTxHashLink && {
        name: translate('notification.common.viewTxHash', locale),
        title: translate('notification.common.viewTxHash', locale),
        link: viewTxHashLink,
      },
    ].filter(Boolean);

    const template: BaseEmailTemplateType = {
      title: translate('notification.subscriptionRefundSucceeded.title', locale, {
        productName,
      }),
      body: translate('notification.subscriptionRefundSucceeded.body', locale, {
        at,
        productName,
        refundInfo,
      }),
      // @ts-expect-error
      attachments: [
        {
          type: 'section',
          fields: [...commonFields, ...amountFields, ...validityPeriodFields, ...refundPeriodFields].filter(Boolean),
        },
      ].filter(Boolean),
      // @ts-ignore
      actions,
    };

    return template;
  }

  private getStakeReturnTemplate(context: SubscriptionRefundSucceededEmailTemplateContext): BaseEmailTemplateType {
    const { locale, productName, at, userDid, refundInfo, viewSubscriptionLink, viewTxHashLink, isCreditSubscription } =
      context;

    // 构建字段
    const commonFields = this.buildCommonFields(userDid, productName, locale);

    // 返还金额字段
    const returnAmountFields = isCreditSubscription
      ? []
      : [
          {
            type: 'text',
            data: {
              type: 'plain',
              color: '#9397A1',
              text: translate('notification.common.returnAmount', locale),
            },
          },
          {
            type: 'text',
            data: {
              type: 'plain',
              text: refundInfo,
            },
          },
        ];

    // 构建操作按钮
    const actions = [
      viewSubscriptionLink && {
        name: translate('notification.common.viewSubscription', locale),
        title: translate('notification.common.viewSubscription', locale),
        link: viewSubscriptionLink,
      },
      viewTxHashLink && {
        name: translate('notification.common.viewTxHash', locale),
        title: translate('notification.common.viewTxHash', locale),
        link: viewTxHashLink,
      },
    ].filter(Boolean);

    return {
      title: translate('notification.subscriptionStakeReturnSucceeded.title', locale, {
        productName,
      }),
      body: translate('notification.subscriptionStakeReturnSucceeded.body', locale, {
        at,
        productName,
        refundInfo,
      }),
      attachments: [
        {
          type: 'section',
          fields: [...commonFields, ...returnAmountFields].filter(Boolean),
        },
      ],
      // @ts-ignore
      actions,
    };
  }
}
