/* eslint-disable @typescript-eslint/brace-style */
/* eslint-disable @typescript-eslint/indent */
import { getUserLocale } from '../../../integrations/blocklet/notification';
import { translate } from '../../../locales';
import { CreditGrant, Customer, PaymentCurrency } from '../../../store/models';
import { formatTime } from '../../time';
import { formatCreditAmount, formatTokenAmount, getCustomerIndexUrl } from '../../util';
import type { BaseEmailTemplate, BaseEmailTemplateType } from './base';

export interface CustomerCreditGrantGrantedEmailTemplateOptions {
  creditGrantId: string;
}

interface CustomerCreditGrantGrantedEmailTemplateContext {
  locale: string;
  userDid: string;
  currencySymbol: string;
  grantedAmount: string;
  expiresAt?: string;
  neverExpires: boolean;
  at: string;
}

export class CustomerCreditGrantGrantedEmailTemplate
  implements BaseEmailTemplate<CustomerCreditGrantGrantedEmailTemplateContext>
{
  options: CustomerCreditGrantGrantedEmailTemplateOptions;

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

  async getContext(): Promise<CustomerCreditGrantGrantedEmailTemplateContext> {
    const creditGrant = await CreditGrant.findByPk(this.options.creditGrantId);
    if (!creditGrant) {
      throw new Error(`CreditGrant not found: ${this.options.creditGrantId}`);
    }

    const customer = await Customer.findByPk(creditGrant.customer_id);
    if (!customer) {
      throw new Error(`Customer not found: ${creditGrant.customer_id}`);
    }

    const paymentCurrency = await PaymentCurrency.findByPk(creditGrant.currency_id);
    if (!paymentCurrency) {
      throw new Error(`PaymentCurrency not found: ${creditGrant.currency_id}`);
    }

    const userDid = customer.did;
    const locale = await getUserLocale(userDid);
    const currencySymbol = paymentCurrency.symbol;
    const at = formatTime(Date.now());

    const neverExpires = !creditGrant.expires_at;
    const expiresAt = creditGrant.expires_at ? formatTime(creditGrant.expires_at * 1000) : undefined;

    return {
      locale,
      userDid,
      currencySymbol,
      grantedAmount: formatCreditAmount(
        formatTokenAmount(creditGrant.amount.toString(), paymentCurrency.decimal) || '0',
        currencySymbol
      ),
      expiresAt,
      neverExpires,
      at,
    };
  }

  async getTemplate(): Promise<BaseEmailTemplateType> {
    const context = await this.getContext();
    const { locale, userDid, grantedAmount, expiresAt, neverExpires, at } = context;

    // 构建字段
    const 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.creditGrantGranted.grantedCredit', locale),
        },
      },
      {
        type: 'text',
        data: {
          type: 'plain',
          text: `${grantedAmount}`,
        },
      },
      {
        type: 'text',
        data: {
          type: 'plain',
          color: '#9397A1',
          text: translate('notification.creditGrantGranted.validUntil', locale),
        },
      },
      {
        type: 'text',
        data: {
          type: 'plain',
          text: neverExpires
            ? translate('notification.creditGrantGranted.neverExpires', locale)
            : (expiresAt as string),
        },
      },
    ];

    const template: BaseEmailTemplateType = {
      title: translate('notification.creditGrantGranted.title', locale),
      body: neverExpires
        ? translate('notification.creditGrantGranted.bodyNoExpire', locale, { grantedAmount, at })
        : translate('notification.creditGrantGranted.body', locale, { grantedAmount, at, expiresAt }),
      attachments: [
        {
          type: 'section',
          fields,
        },
      ],
      actions: [
        {
          name: translate('notification.common.viewCreditGrant', locale),
          title: translate('notification.common.viewCreditGrant', locale),
          link: getCustomerIndexUrl({
            locale,
            userDid,
          }),
        },
      ], // 可以根据需要添加操作按钮
    };

    return template;
  }
}
