// apps/api/src/services/search.service.js

const { DatabaseClient } = require('../../../packages/db/client');
const Validators = require('../../../packages/shared/validators');
const leadsService = require('./leads.service');

const db = new DatabaseClient();

class SearchService {
    async search(query, filters = {}) {
        const validation = Validators.validateSearchQuery(query);
        if (!validation.valid) {
            throw new Error(validation.error);
        }
        
        const { location, urgency, source_type, limit = 50 } = filters;
        
        // FIX: Enforce intent confidence filtering and match strictly against your categorized fields
        let sql = `
            SELECT id, title, description, service_needed, location, contact_phone, contact_email,
                   source_url, source_type, urgency_level, confidence_score, score, score_category,
                   posted_date, discovered_at
            FROM leads
            WHERE is_active = 1
            AND confidence_score >= 40
            AND (title LIKE ? OR service_needed LIKE ? OR score_category LIKE ?)
        `;
        
        const params = [`%${query}%`, `%${query}%`, `%${query}%`];
        
        if (location) {
            sql += ' AND location LIKE ?';
            params.push(`%${location}%`);
        }
        
        if (urgency && urgency !== 'all') {
            sql += ' AND urgency_level = ?';
            params.push(urgency);
        }
        
        if (source_type) {
            sql += ' AND source_type = ?';
            params.push(source_type);
        }
        
        sql += ' ORDER BY score DESC, discovered_at DESC LIMIT ?';
        params.push(limit);
        
        const leads = await db.query(sql, params);
        return leads;
    }
    
    async saveSearchHistory(userId, query, resultsCount) {
        await db.run(
            'INSERT INTO search_history (user_id, query, results_count) VALUES (?, ?, ?)',
            [userId, query, resultsCount]
        );
        
        await db.run('UPDATE users SET searches_count = searches_count + 1 WHERE id = ?', [userId]);
    }
    
    async getSearchHistory(userId, limit = 50) {
        return await db.query(
            'SELECT id, query, results_count, created_at FROM search_history WHERE user_id = ? ORDER BY created_at DESC LIMIT ?',
            [userId, limit]
        );
    }
    
    async deleteSearchHistory(userId, historyId) {
        await db.run('DELETE FROM search_history WHERE id = ? AND user_id = ?', [historyId, userId]);
    }
    
    async clearSearchHistory(userId) {
        await db.run('DELETE FROM search_history WHERE user_id = ?', [userId]);
    }
    
    // FIX: Replaced native MySQL syntax with cross-platform JS time strings to protect local executions
    async getPopularSearches(limit = 10) {
        const cutoffDate = new Date();
        cutoffDate.setDate(cutoffDate.getDate() - 30);
        const formattedDate = cutoffDate.toISOString().slice(0, 19).replace('T', ' ');

        return await db.query(
            `SELECT query, COUNT(*) as count 
             FROM search_history 
             WHERE created_at >= ?
             GROUP BY query 
             ORDER BY count DESC 
             LIMIT ?`,
            [formattedDate, limit]
        );
    }
    
    async expandQuery(query) {
        const intentPrefixes = ['need', 'looking for', 'seeking', 'hire', 'want'];
        const expanded = [];
        
        for (const prefix of intentPrefixes) {
            expanded.push(`${prefix} ${query}`);
        }
        
        return expanded;
    }
}

module.exports = new SearchService();