import { apiCreateNotification } from "./api-integrations";
import type { NotificationType } from "./types-integrations";

// Regex to match @mentions in text
const MENTION_REGEX = /@([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}|[a-zA-Z0-9_]+)/g;

export interface Mention {
  text: string;      // The full @mention text
  identifier: string; // The identifier after @ (email or username)
  startIndex: number;
  endIndex: number;
}

/**
 * Parse @mentions from text content
 */
export function parseMentions(text: string): Mention[] {
  const mentions: Mention[] = [];
  let match;
  
  while ((match = MENTION_REGEX.exec(text)) !== null) {
    mentions.push({
      text: match[0],
      identifier: match[1],
      startIndex: match.index,
      endIndex: match.index + match[0].length
    });
  }
  
  return mentions;
}

/**
 * Extract unique identifiers from mentions
 */
export function extractMentionIdentifiers(text: string): string[] {
  const mentions = parseMentions(text);
  return [...new Set(mentions.map(m => m.identifier))];
}

/**
 * Check if text contains any mentions
 */
export function hasMentions(text: string): boolean {
  return MENTION_REGEX.test(text);
}

/**
 * Create notifications for mentioned users
 * @param workspaceSlug - The workspace slug
 * @param mentionerName - Name of the person who mentioned
 * @param entityType - Type of entity (task, note, etc.)
 * @param entityId - ID of the entity
 * @param content - The content containing mentions
 * @param knownEmails - Map of usernames to emails if available
 */
export async function notifyMentionedUsers(
  workspaceSlug: string,
  mentionerName: string,
  entityType: string,
  entityId: string,
  content: string,
  knownEmails?: Map<string, string>
): Promise<void> {
  const identifiers = extractMentionIdentifiers(content);
  
  for (const identifier of identifiers) {
    // If identifier looks like an email, use it directly
    // Otherwise, look it up in knownEmails map
    const email = identifier.includes('@') 
      ? identifier 
      : knownEmails?.get(identifier.toLowerCase());
    
    if (!email) continue;
    
    try {
      await apiCreateNotification({
        workspaceSlug,
        userEmail: email,
        type: "mention" as NotificationType,
        title: `${mentionerName} mentioned you`,
        body: content.slice(0, 100) + (content.length > 100 ? '...' : ''),
        entityType,
        entityId
      });
    } catch (e) {
      console.error('Failed to create mention notification:', e);
    }
  }
}

/**
 * Highlight mentions in text for display
 * Returns HTML string with mentions wrapped in spans
 */
export function highlightMentions(text: string): string {
  return text.replace(MENTION_REGEX, '<span class="mention text-[var(--accent)] font-medium">$&</span>');
}