const express = require('express');
const router = express.Router();
const db = require('../db');
const jwt = require('jsonwebtoken');

// Middleware to verify User
const authenticateUser = (req, res, next) => {
    const authHeader = req.headers.authorization;
    if (!authHeader) return res.status(401).json({ success: false, message: 'No token provided' });

    const token = authHeader.split(' ')[1];
    try {
        const decoded = jwt.verify(token, process.env.JWT_SECRET || 'anjaneyulu_secret_123');
        req.user = decoded;
        next();
    } catch (err) {
        return res.status(401).json({ success: false, message: 'Invalid token' });
    }
};

// Create a new lead
router.post('/', async (req, res) => {
    const { lead_type, user_id, full_name, mobile, email, service_interested, loan_amount, net_salary, company_name, employment_type, city, state, pincode, metadata } = req.body;

    let finalUserId = user_id;

    // Check if token exists to automatically associate the lead with the logged-in user
    const authHeader = req.headers.authorization;
    if (authHeader && authHeader.startsWith('Bearer ')) {
        const token = authHeader.split(' ')[1];
        try {
            const decoded = jwt.verify(token, process.env.JWT_SECRET || 'anjaneyulu_secret_123');
            finalUserId = decoded.id;
        } catch (e) {
            // ignore invalid token for optional user association
        }
    }

    try {
        const result = await db.query(
            `INSERT INTO leads (lead_type, user_id, full_name, mobile, email, service_interested, loan_amount, net_salary, company_name, employment_type, city, state, pincode, metadata)
       VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)
       RETURNING *`,
            [lead_type, finalUserId, full_name, mobile, email, service_interested, loan_amount, net_salary, company_name, employment_type, city, state, pincode, metadata]
        );

        res.status(201).json({ success: true, lead: result.rows[0] });
    } catch (err) {
        console.error(err);
        res.status(500).json({ success: false, message: 'Error creating lead' });
    }
});

// Get leads (Filtered by Role)
router.get('/', authenticateUser, async (req, res) => {
    try {
        let result;
        const isAdmin = req.user.role === 'admin' || req.user.role === 'super_admin' || req.user.role === 'sub_admin';

        if (isAdmin) {
            result = await db.query('SELECT * FROM leads ORDER BY created_at DESC');
        } else {
            result = await db.query('SELECT * FROM leads WHERE user_id = $1 ORDER BY created_at DESC', [req.user.id]);
        }
        res.json({ success: true, leads: result.rows });
    } catch (err) {
        console.error(err);
        res.status(500).json({ success: false, message: 'Error fetching leads' });
    }
});

// Update lead status (Allowed for admin OR lead owner)
router.patch('/:id/status', authenticateUser, async (req, res) => {
    const { id } = req.params;
    const { status, sub_stage } = req.body;
    try {
        const leadCheck = await db.query('SELECT user_id FROM leads WHERE id = $1', [id]);
        if (leadCheck.rows.length === 0) {
            return res.status(404).json({ success: false, message: 'Lead not found' });
        }

        const lead = leadCheck.rows[0];
        const isAdmin = req.user.role === 'admin' || req.user.role === 'super_admin' || req.user.role === 'sub_admin';

        if (!isAdmin && lead.user_id !== req.user.id) {
            return res.status(403).json({ success: false, message: 'Unauthorized to update this lead' });
        }

        const result = await db.query(
            'UPDATE leads SET status = $1, sub_stage = $2, pending_status = \'None\', updated_at = CURRENT_TIMESTAMP WHERE id = $3 RETURNING *',
            [status, sub_stage, id]
        );
        res.json({ success: true, lead: result.rows[0] });
    } catch (err) {
        console.error(err);
        res.status(500).json({ success: false, message: 'Error updating lead' });
    }
});

// Update lead pending status (Admin/Processing team only)
router.patch('/:id/pending', authenticateUser, async (req, res) => {
    const { id } = req.params;
    const { pending_status, pending_remarks } = req.body;

    const isAdmin = req.user.role === 'admin' || req.user.role === 'super_admin' || req.user.role === 'sub_admin';
    if (!isAdmin) {
        return res.status(403).json({ success: false, message: 'Unauthorized to modify pending status' });
    }

    try {
        const result = await db.query(
            'UPDATE leads SET pending_status = $1, pending_remarks = $2, updated_at = CURRENT_TIMESTAMP WHERE id = $3 RETURNING *',
            [pending_status, pending_remarks, id]
        );
        if (result.rows.length === 0) {
            return res.status(404).json({ success: false, message: 'Lead not found' });
        }
        res.json({ success: true, lead: result.rows[0] });
    } catch (err) {
        console.error(err);
        res.status(500).json({ success: false, message: 'Error updating pending status' });
    }
});

module.exports = router;
