// Domain Reputation Detector - Analyzes domain patterns for suspicious characteristics
// Migrated from legacy url-rules.js domain pattern detection

import { BaseDetector } from '../base-detector.js';

export class DomainReputationDetector extends BaseDetector {
  constructor(config = {}) {
    super({
      name: 'domain-reputation',
      category: 'url',
      version: '1.0.0',
      description: 'Detects suspicious domain patterns including single-word domains, numeric domains, and free/suspicious TLDs',
      weight: 2,
      severity: 'medium',
      ...config
    });
  }

  async detect(target, ruleRegistry) {
    if (!target.url) {
      return this.createResult(false, [], 0);
    }

    const findings = [];
    const domain = this.extractDomain(target.url);

    if (!domain) {
      return this.createResult(false, [], 0);
    }

    // Get rules from registry
    const rules = ruleRegistry.getRules('url', 'domain-patterns');

    if (!rules || !rules.patterns) {
      console.warn('[domain-reputation] No rules loaded');
      return this.createResult(false, [], 0);
    }

    // Check each domain pattern
    for (const rule of rules.patterns) {
      if (rule.regex && this.testPattern(rule.regex, domain)) {
        findings.push(this.createFinding({
          pattern: rule.pattern,
          matched: domain,
          description: rule.description || 'Suspicious domain pattern detected',
          severity: rule.severity || 'medium',
          weight: rule.weight || 2,
          metadata: {
            ruleId: rule.id,
            domain
          }
        }));
      }
    }

    // Check against known target domains (phishing targets)
    if (rules.targetDomains && Array.isArray(rules.targetDomains)) {
      if (rules.targetDomains.includes(domain)) {
        findings.push(this.createFinding({
          pattern: 'target-domain',
          matched: domain,
          description: 'Domain is a common phishing target',
          severity: 'high',
          weight: 3,
          metadata: {
            domain,
            isTarget: true
          }
        }));
      }
    }

    const matched = findings.length > 0;
    const riskScore = findings.reduce((sum, f) => sum + (f.weight || 1), 0);

    return this.createResult(matched, findings, riskScore);
  }
}
