import { Injectable, Logger } from '@nestjs/common';

export interface TaskNotifyPayload {
  event: string;
  taskId: number;
  hospitalId: number;
  actorId: number;
  status: string;
}

@Injectable()
export class WechatNotifyService {
  private readonly logger = new Logger(WechatNotifyService.name);

  /**
   * 任务通知发送入口：后续可在此接入微信服务号/小程序订阅消息 API。
   */
  async notifyTaskChange(
    openIds: Array<string | null | undefined>,
    payload: TaskNotifyPayload,
  ) {
    const targets = Array.from(
      new Set(
        openIds
          .map((item) => item?.trim())
          .filter((item): item is string => Boolean(item)),
      ),
    );

    if (targets.length === 0) {
      this.logger.warn(
        `任务事件 ${payload.event} 无可用 openId，taskId=${payload.taskId}`,
      );
      return;
    }

    for (const openId of targets) {
      const maskedOpenId = this.maskOpenId(openId);
      // TODO: 在此处调用微信服务号/小程序消息推送 API。
      this.logger.log(
        `模拟推送任务通知 event=${payload.event}, taskId=${payload.taskId}, openId=${maskedOpenId}`,
      );
    }
  }

  /**
   * 日志脱敏：仅保留 openId 首尾片段，避免完整标识泄露。
   */
  private maskOpenId(openId: string) {
    if (openId.length <= 6) {
      return '***';
    }

    return `${openId.slice(0, 3)}***${openId.slice(-3)}`;
  }
}
