import Taro from '@tarojs/taro';

import { SubscribeTempId } from '@/constants/subscribe';
import http from '@/http';
import { API } from '@/http/api';
import { logWithPrefix } from '@/utils/common';

const log = logWithPrefix('subscribe-utils');

export const isSubscribeRefused = async (tempId: SubscribeTempId | SubscribeTempId[]) => {
  tempId = Array.isArray(tempId) ? tempId : [tempId];
  const { subscriptionsSetting } = await Taro.getSetting({ withSubscriptions: true });
  log('isSubscribeRefuse subscriptionsSetting:', subscriptionsSetting);
  if (!subscriptionsSetting) {
    return false;
  }
  const { mainSwitch, itemSettings = {} } = subscriptionsSetting;
  if (!mainSwitch) {
    return true;
  }
  return tempId.some(id => {
    const item = itemSettings[id];
    if (!item) {
      return false;
    }
    return item === 'reject';
  });
};

export const subscribeMessage = async (tempIds: SubscribeTempId[]) => {
  return Taro.requestSubscribeMessage({
    tmplIds: tempIds,
    entityIds: [],
  });
};

export const postSubscribe = (tempIds: SubscribeTempId[], acceptTempIds: SubscribeTempId[]) => {
  const data = { templateIds: tempIds, subscribeIds: acceptTempIds };
  log('postSubscribe', data);
  return http.post(API.SUBSCRIBE, { data });
};
