// apps/api/src/controllers/leads.controller.js

const { DatabaseClient } = require('../../../../packages/db/client');
const Helpers = require('../../../../packages/shared/helpers');

const db = new DatabaseClient();

exports.getLeads = async (req, res) => {
    try {
        console.log('req.leadLimit from middleware:', req.leadLimit);
        
        const { service, location, score_category, sort } = req.query;
        
        let whereClause = 'WHERE 1=1';
        const params = [];
        
        if (service) {
            whereClause += ' AND (service_needed LIKE ? OR title LIKE ? OR description LIKE ?)';
            const searchTerm = `%${service}%`;
            params.push(searchTerm, searchTerm, searchTerm);
        }
        
        if (location) {
            whereClause += ' AND location LIKE ?';
            params.push(`%${location}%`);
        }
        
        if (score_category) {
            whereClause += ' AND score_category = ?';
            params.push(score_category);
        }
        
        const orderBy = sort === 'recent' ? 'discovered_at DESC' : 'score DESC';
        
        // For free users: only 10 leads total, no pagination
        if (req.leadLimit && req.leadLimit === 10) {
            const leads = await db.query(
                `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 
                 ${whereClause}
                 ORDER BY ${orderBy}
                 LIMIT 10`,
                params
            );
            
            await db.run('UPDATE users SET leads_viewed = leads_viewed + 1 WHERE id = ?', [req.user.id]);
            
            return res.json({
                leads: leads.map(lead => ({
                    ...lead,
                    time_ago: Helpers.timeAgo(lead.discovered_at)
                })),
                pagination: {
                    page: 1,
                    limit: 10,
                    total: leads.length,
                    pages: 1
                },
                user_plan: 'free'
            });
        }
        
        // Pro users: full pagination
        const page = parseInt(req.query.page) || 1;
        const limit = parseInt(req.query.limit) || 20;
        const offset = (page - 1) * limit;
        
        const leads = await db.query(
            `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 
             ${whereClause}
             ORDER BY ${orderBy}
             LIMIT ? OFFSET ?`,
            [...params, limit, offset]
        );
        
        const countResult = await db.get(
            `SELECT COUNT(*) as total FROM leads ${whereClause}`,
            params
        );
        
        await db.run('UPDATE users SET leads_viewed = leads_viewed + 1 WHERE id = ?', [req.user.id]);
        
        res.json({
            leads: leads.map(lead => ({
                ...lead,
                time_ago: Helpers.timeAgo(lead.discovered_at)
            })),
            pagination: {
                page,
                limit,
                total: countResult.total,
                pages: Math.ceil(countResult.total / limit)
            },
            user_plan: 'pro'
        });
    } catch (error) {
        console.error('Get leads error:', error);
        res.status(500).json({ error: 'Failed to get leads' });
    }
};

exports.getLead = async (req, res) => {
    try {
        const lead = await db.get(
            `SELECT l.*, 
                    (SELECT COUNT(*) FROM bookmarks WHERE lead_id = l.id AND user_id = ?) as is_bookmarked
             FROM leads l
             WHERE l.id = ?`,
            [req.user.id, req.params.id]
        );
        
        if (!lead) {
            return res.status(404).json({ error: 'Lead not found' });
        }
        
        // Increment display count
        await db.run('UPDATE leads SET times_displayed = times_displayed + 1 WHERE id = ?', [req.params.id]);
        
        res.json(lead);
    } catch (error) {
        console.error('Get lead error:', error);
        res.status(500).json({ error: 'Failed to get lead' });
    }
};

exports.submitFeedback = async (req, res) => {
    try {
        const { quality_score, is_relevant, notes } = req.body;
        const leadId = req.params.id;
        
        await db.run(
            `INSERT INTO signal_feedback (lead_id, user_id, quality_score, is_relevant, notes)
             VALUES (?, ?, ?, ?, ?)
             ON CONFLICT(user_id, lead_id) DO UPDATE SET 
                quality_score = excluded.quality_score, 
                is_relevant = excluded.is_relevant, 
                notes = excluded.notes`,
            [leadId, req.user.id, quality_score, is_relevant, notes]
        );
        
        res.json({ message: 'Feedback submitted successfully' });
    } catch (error) {
        console.error('Submit feedback error:', error);
        res.status(500).json({ error: 'Failed to submit feedback' });
    }
};

exports.exportCSV = async (req, res) => {
    try {
        // Check if user is pro
        const user = await db.get('SELECT plan FROM users WHERE id = ?', [req.user.id]);
        if (user.plan !== 'pro') {
            return res.status(403).json({ error: 'Export feature is only available for Pro users. Upgrade to access this feature.' });
        }
        
        const leads = await db.query(
            `SELECT title, description, service_needed, location, contact_phone, contact_email,
                    source_url, urgency_level, score_category, discovered_at
             FROM leads
             WHERE is_active = 1
             ORDER BY discovered_at DESC
             LIMIT 10000`
        );
        
        let csv = 'Title,Description,Service Needed,Location,Phone,Email,Source URL,Urgency,Score Category,Discovered At\n';
        
        for (const lead of leads) {
            csv += `"${(lead.title || '').replace(/"/g, '""')}",`;
            csv += `"${(lead.description || '').replace(/"/g, '""')}",`;
            csv += `"${lead.service_needed || ''}",`;
            csv += `"${lead.location || ''}",`;
            csv += `"${lead.contact_phone || ''}",`;
            csv += `"${lead.contact_email || ''}",`;
            csv += `"${lead.source_url || ''}",`;
            csv += `${lead.urgency_level || ''},`;
            csv += `${lead.score_category || ''},`;
            csv += `${lead.discovered_at}\n`;
        }
        
        res.setHeader('Content-Type', 'text/csv');
        res.setHeader('Content-Disposition', `attachment; filename=leads_${Date.now()}.csv`);
        res.send(csv);
    } catch (error) {
        console.error('Export CSV error:', error);
        res.status(500).json({ error: 'Failed to export CSV' });
    }
};

exports.exportJSON = async (req, res) => {
    try {
        // Check if user is pro
        const user = await db.get('SELECT plan FROM users WHERE id = ?', [req.user.id]);
        if (user.plan !== 'pro') {
            return res.status(403).json({ error: 'Export feature is only available for Pro users. Upgrade to access this feature.' });
        }
        
        const leads = await db.query(
            `SELECT id, title, description, service_needed, location, contact_phone, contact_email,
                    contact_whatsapp, source_url, source_type, urgency_level, budget_hint,
                    confidence_score, score, score_category, posted_date, discovered_at
             FROM leads
             WHERE is_active = 1
             ORDER BY discovered_at DESC
             LIMIT 10000`
        );
        
        res.setHeader('Content-Type', 'application/json');
        res.setHeader('Content-Disposition', `attachment; filename=leads_${Date.now()}.json`);
        res.json(leads);
    } catch (error) {
        console.error('Export JSON error:', error);
        res.status(500).json({ error: 'Failed to export JSON' });
    }
};