export class GroupInteractionDeclineError extends Error {
  readonly isInteractionDecline = true;
  constructor(public readonly declineMessage: string) {
    super(declineMessage);
    this.name = 'GroupInteractionDeclineError';
    Object.setPrototypeOf(this, GroupInteractionDeclineError.prototype);
  }
}

export function withClarifyTimeout<T>(
  promise: Promise<T>,
  timeoutMs: number,
): Promise<T> {
  let timer: ReturnType<typeof setTimeout> | undefined;
  const timeout = new Promise<T>((_, reject) => {
    timer = setTimeout(() => {
      reject(
        new GroupInteractionDeclineError(
          '⏱️ 等待 5 分钟未收到回复，已自动取消本次询问',
        ),
      );
    }, timeoutMs);
  });

  return Promise.race([
    promise.then(
      value => {
        if (timer) clearTimeout(timer);
        return value;
      },
      reason => {
        if (timer) clearTimeout(timer);
        throw reason;
      },
    ),
    timeout,
  ]);
}
