// apps/api/src/scrapers/parser.js

class ResultParser {
    parseSearchResult(result) {
        if (!result) return null;
        return {
            raw: result,
            title: this.cleanText(result.title || ''),
            description: this.cleanText(result.snippet || result.description || ''),
            url: this.validateUrl(result.url || ''),
            source: result.source || 'unassigned-source',
            metadata: {
                hasContact: this.hasContactInfo(result),
                hasPrice: this.hasPrice(result),
                timestamp: result.timestamp || new Date()
            }
        };
    }
    
    cleanText(text) {
        if (!text) return '';
        return text
            .replace(/\s+/g, ' ')
            .replace(/[^\w\s@\-.,/#!$%?&:;=+~]/g, '')
            .trim();
    }
    
    validateUrl(url) {
        if (!url) return null;
        if (url.startsWith('http')) return url;
        if (url.startsWith('/')) return null;
        return url;
    }
    
    hasContactInfo(result) {
        const text = `${result.title || ''} ${result.snippet || result.description || ''}`.toLowerCase();
        return text.includes('@') || 
               text.includes('phone') || 
               text.includes('whatsapp') ||
               /\d{10,}/.test(text);
    }
    
    hasPrice(result) {
        const text = `${result.title || ''} ${result.snippet || result.description || ''}`.toLowerCase();
        return text.includes('ksh') || 
               text.includes('usd') || 
               text.includes('price') ||
               /[\d,]+/.test(text);
    }
}

module.exports = new ResultParser();