import Notification from '@blocklet/sdk/service/notification';
import { toDid } from '@ocap/util';
import { get } from 'lodash';
import type { LiteralUnion } from 'type-fest';

import { blocklet } from '../../libs/auth';
import logger from '../../libs/logger';
import { translate } from '../../locales';

export const getUserLocale = async (userDid: string): Promise<LiteralUnion<'zh' | 'en', string>> => {
  const { user } = await blocklet.getUser(userDid);
  return get(user, 'locale', 'en');
};

export function createInfoRows(info: any = {}) {
  const fields = Object.keys(info).reduce((list, cur) => {
    const item = info[cur];
    const data = {
      type: 'plain',
      text: item,
      color: undefined,
    };

    if (Array.isArray(item)) {
      const [text, color] = item;
      data.text = text;
      if (color) {
        data.color = color;
      }
    }

    if (typeof data.text !== 'string') {
      data.text = String(data.text);
    }

    list.push(
      // @ts-ignore
      {
        type: 'text',
        data: {
          type: 'plain',
          color: '#9397A1',
          text: cur,
        },
      },
      {
        type: 'text',
        data,
      }
    );
    return list;
  }, []);

  return {
    type: 'section',
    fields,
  };
}

export async function sendNotification({
  to,
  title,
  message,
  actions,
  attachments = [],
  allowUnsubscribe = false, // 是否允许用户取消订阅，如果为false，则用户无法取消订阅，用户总会收到邮件
}: {
  to: string;
  title: string;
  message: string;
  actions: any[];
  attachments: any[];
  allowUnsubscribe?: boolean;
}) {
  try {
    const payload = { title, body: message, actions: actions || [], attachments: [...attachments] };
    await Notification.sendToUser(to, payload, { allowUnsubscribe });
    logger.info('text message was sent', { to, payload: JSON.stringify(payload, null, 2) });
  } catch (error) {
    logger.error('send text message failed', { error, to, message, actions, attachments });
    throw error;
  }
}

export async function sendNftNotification(nftDid: string, userDid: string, chainHost: string, collection: string) {
  const locale = await getUserLocale(userDid);
  await sendNotification({
    to: userDid,
    title: translate('notification.mintNFT.title', locale, { collection }),
    message: translate('notification.mintNFT.message', locale, { collection }),
    attachments: [
      {
        type: 'asset',
        data: {
          chainHost,
          did: nftDid,
        },
      },
      createInfoRows({
        [translate('notification.sendTo', locale)]: toDid(userDid),
      }),
    ],
    actions: [],
  });
}
