import prettyMsI18n from 'pretty-ms-i18n';
import { getOwnerDid } from '../../util';
import { translate } from '../../../locales';
import { Subscription } from '../../../store/models';
import type { BaseEmailTemplate, BaseEmailTemplateType } from './base';
import { getUserLocale } from '../../../integrations/blocklet/notification';
import { formatTime, getPrettyMsI18nLocale } from '../../time';
import { getMainProductName } from '../../product';
import { checkUsageReportEmpty, getAdminSubscriptionPageUrl } from '../../subscription';

export interface UsageReportEmptyEmailTemplateOptions {
  subscriptionId: string;
  usageReportStart: number;
  usageReportEnd: number;
}

interface UsageReportEmptyEmailTemplateContext {
  locale: string;
  userDid: string;
  productName: string;
  subscriptionId: string;
  currentPeriodStart: string;
  currentPeriodEnd: string;
  viewSubscriptionLink: string;
  duration: string;
}

export class UsageReportEmptyEmailTemplate implements BaseEmailTemplate<UsageReportEmptyEmailTemplateContext> {
  options: UsageReportEmptyEmailTemplateOptions;

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

  async getContext(): Promise<UsageReportEmptyEmailTemplateContext> {
    const { usageReportStart, usageReportEnd, subscriptionId } = this.options;
    const subscription: Subscription | null = await Subscription.findByPk(subscriptionId);
    if (!subscription) {
      throw new Error(`Subscription not found: ${subscriptionId}`);
    }
    const userDid = await getOwnerDid();
    if (!userDid) {
      throw new Error('get owner did failed');
    }
    const usageReportEmpty = await checkUsageReportEmpty(subscription, usageReportStart, usageReportEnd);
    if (!usageReportEmpty) {
      throw new Error('Usage report is not empty, no need to send email');
    }
    const locale = await getUserLocale(userDid);
    const productName = await getMainProductName(subscription.id);
    const currentPeriodStart = formatTime(subscription.current_period_start * 1000);
    const currentPeriodEnd = formatTime(subscription.current_period_end * 1000);
    const duration: string = prettyMsI18n(
      new Date(currentPeriodEnd).getTime() - new Date(currentPeriodStart).getTime(),
      {
        locale: getPrettyMsI18nLocale(locale),
      }
    );
    const viewSubscriptionLink = getAdminSubscriptionPageUrl({
      subscriptionId: subscription.id,
      locale,
      userDid,
    });
    return {
      userDid,
      locale,
      productName,
      subscriptionId: subscription.id,
      currentPeriodStart,
      currentPeriodEnd,
      viewSubscriptionLink,
      duration,
    };
  }

  async getTemplate(): Promise<BaseEmailTemplateType> {
    const {
      locale,
      productName,
      subscriptionId,
      currentPeriodStart,
      currentPeriodEnd,
      viewSubscriptionLink,
      duration,
    } = await this.getContext();

    const template: BaseEmailTemplateType = {
      title: translate('notification.usageReportEmpty.title', locale, {
        productName,
      }),
      body: translate('notification.usageReportEmpty.body', locale, {
        productName,
      }),
      attachments: [
        {
          type: 'section',
          fields: [
            {
              type: 'text',
              data: {
                type: 'plain',
                color: '#9397A1',
                text: translate('notification.common.product', locale),
              },
            },
            {
              type: 'text',
              data: {
                type: 'plain',
                text: productName,
              },
            },
            {
              type: 'text',
              data: {
                type: 'plain',
                color: '#9397A1',
                text: translate('notification.common.subscriptionId', locale),
              },
            },
            {
              type: 'text',
              data: {
                type: 'plain',
                text: subscriptionId,
              },
            },
            {
              type: 'text',
              data: {
                type: 'plain',
                color: '#9397A1',
                text: translate('notification.common.validityPeriod', locale),
              },
            },
            {
              type: 'text',
              data: {
                type: 'plain',
                text: `${currentPeriodStart} ~ ${currentPeriodEnd}(${duration})`,
              },
            },
          ].filter(Boolean),
        },
      ],
      // @ts-ignore
      actions: [
        {
          name: translate('notification.common.viewSubscription', locale),
          title: translate('notification.common.viewSubscription', locale),
          link: viewSubscriptionLink,
        },
      ].filter(Boolean),
    };

    return template;
  }
}
