'use strict';

const SLACK_USER_MENTION_RE = /<@[A-Z0-9]+>/gi;
const WALLE_AT_MENTION_RE = /@wall-?e\b/i;
const WALLE_AT_MENTION_GLOBAL_RE = /@wall-?e\b\s*[:,;.!?]?\s*/gi;
const GREETING_ACTIVATION_RE = /^\s*(hi|hey|hello)\s*,?\s+wall-?e\b\s*[:,;.!?]?\s*/i;
const GREETING_CLEAN_RE = /^\s*(hi|hey|hello)\s*,?\s+wall-?e\b\s*[:,;.!?]?\s*([\s\S]*)$/i;

function normalizeWalleAddress(text, opts = {}) {
  const value = String(text || '');
  if (!opts.allowSlackMentions) return value;
  return value.replace(SLACK_USER_MENTION_RE, '@walle');
}

function hasWalleActivation(text, opts = {}) {
  const normalized = normalizeWalleAddress(text, opts);
  return WALLE_AT_MENTION_RE.test(normalized) || GREETING_ACTIVATION_RE.test(normalized);
}

function cleanWalleAddressText(text, opts = {}) {
  const normalized = normalizeWalleAddress(text, opts).trim();
  const greeting = normalized.match(GREETING_CLEAN_RE);
  if (greeting) {
    const rest = String(greeting[2] || '').trim();
    return rest || greeting[1].trim();
  }
  return normalized.replace(WALLE_AT_MENTION_GLOBAL_RE, '').trim();
}

module.exports = {
  cleanWalleAddressText,
  hasWalleActivation,
  normalizeWalleAddress,
};
