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

// Middleware to verify JWT and check for admin or super_admin
const authenticateAdmin = (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');
        if (decoded.role !== 'admin' && decoded.role !== 'super_admin') {
            return res.status(403).json({ success: false, message: 'Admin access required' });
        }
        req.user = decoded;
        next();
    } catch (err) {
        return res.status(401).json({ success: false, message: 'Invalid token' });
    }
};

// Get all users
router.get('/', authenticateAdmin, async (req, res) => {
    try {
        const result = await db.query(`
            SELECT 
                id, unique_user_id, name, mobile, email, whatsapp_number,
                gender, age, occupation,
                present_address, permanent_address,
                role, status, created_at,
                referred_by_name, referred_by_mobile
            FROM users 
            ORDER BY created_at DESC
        `);
        res.json({ success: true, users: result.rows });
    } catch (err) {
        console.error(err);
        res.status(500).json({ success: false, message: 'Server error' });
    }
});

// Update user role (Role Promotion with Assignment Form)
router.patch('/:id/promote', authenticateAdmin, async (req, res) => {
    const { id } = req.params;
    const {
        role,
        email,
        gender,
        age,
        whatsapp_number,
        occupation,
        photo_url,
        pan_card_url,
        aadhaar_front_url,
        aadhaar_back_url,
        present_address,
        permanent_address,
        referred_by_name,
        referred_by_mobile,
        additional_details
    } = req.body;

    try {
        // Enforce role promotion rules: Only Admin/SuperAdmin can promote, cannot modify SuperAdmin
        const userToUpdate = await db.query('SELECT role FROM users WHERE id = $1', [id]);
        if (userToUpdate.rows[0].role === 'super_admin') {
            return res.status(403).json({ success: false, message: 'Cannot modify Super Admin access' });
        }

        await db.query(
            `UPDATE users SET 
                role = $1, email = $2, gender = $3, age = $4, 
                whatsapp_number = $5, occupation = $6, photo_url = $7, 
                pan_card_url = $8, aadhaar_front_url = $9, aadhaar_back_url = $10, 
                present_address = $11, permanent_address = $12, 
                referred_by_name = $13, referred_by_mobile = $14, 
                additional_details = $15, updated_at = CURRENT_TIMESTAMP
            WHERE id = $16`,
            [
                role, email, gender, age,
                whatsapp_number, occupation, photo_url,
                pan_card_url, aadhaar_front_url, aadhaar_back_url,
                JSON.stringify(present_address), JSON.stringify(permanent_address),
                referred_by_name, referred_by_mobile,
                additional_details, id
            ]
        );

        // Log the promotion
        await db.query(
            'INSERT INTO audit_logs (action_type, actor_id, details) VALUES ($1, $2, $3)',
            ['role_promotion', req.user.id, JSON.stringify({ promoted_user_id: id, new_role: role })]
        );

        res.json({ success: true, message: 'User role updated successfully' });
    } catch (err) {
        console.error(err);
        res.status(500).json({ success: false, message: 'Server error during promotion' });
    }
});

// Toggle user status
router.patch('/:id/status', authenticateAdmin, async (req, res) => {
    const { id } = req.params;
    const { status } = req.body;
    try {
        await db.query('UPDATE users SET status = $1 WHERE id = $2', [status, id]);
        res.json({ success: true, message: 'User status updated' });
    } catch (err) {
        console.error(err);
        res.status(500).json({ success: false, message: 'Server error' });
    }
});

module.exports = router;
