import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';

export interface ModerationResult { flagged: boolean; score: number; reasons: string[] }

@Injectable()
export class ContentModerationService {
  constructor(private readonly config: ConfigService) {}

  analyze(text: string): ModerationResult {
    const normalized = text.toLowerCase().replace(/\s+/g, ' ').trim();
    const reasons: string[] = [];
    let score = 0;
    const terms = this.config.get<string[]>('moderation.blockedTerms') ?? [];
    const matchedTerms = terms.filter((term) => term && normalized.includes(term));
    if (matchedTerms.length) {
      score += Math.min(8, matchedTerms.length * 4);
      reasons.push('blocked_terms');
    }
    const urls = normalized.match(/https?:\/\/|www\./g)?.length ?? 0;
    if (urls >= 3) { score += 3; reasons.push('excessive_links'); }
    if (/(.)\1{9,}/u.test(normalized)) { score += 2; reasons.push('repeated_characters'); }
    if (normalized.length > 40) {
      const tokens = normalized.split(' ');
      const uniqueRatio = new Set(tokens).size / tokens.length;
      if (uniqueRatio < 0.25) { score += 2; reasons.push('repetitive_text'); }
    }
    return { flagged: score >= 5, score, reasons };
  }
}
