const User = require('../models/User');
const Product = require('../models/Product');
const Redemption = require('../models/Redemption');

// Get user's referral statistics
const getUserReferralStats = async (req, res) => {
    try {
        const userId = req.user.id;
        
        const user = await User.findById(userId).select('referralCode coins totalReferrals successfulReferrals');
        
        if (!user) {
            return res.status(404).json({
                success: false,
                message: 'User not found'
            });
        }

        // Get users referred by this user
        const referredUsers = await User.find({ referredBy: userId })
            .select('name mobile createdAt')
            .sort({ createdAt: -1 });

        res.json({
            success: true,
            data: {
                referralCode: user.referralCode,
                coins: user.coins,
                totalReferrals: user.totalReferrals,
                successfulReferrals: user.successfulReferrals,
                referredUsers: referredUsers
            }
        });
    } catch (error) {
        console.error('Get referral stats error:', error);
        res.status(500).json({
            success: false,
            message: 'Internal server error'
        });
    }
};

// Add coins for successful referral
const addReferralCoins = async (req, res) => {
    try {
        const { userId, coinsToAdd = 20 } = req.body;
        
        if (!userId) {
            return res.status(400).json({
                success: false,
                message: 'User ID is required'
            });
        }

        const user = await User.findById(userId);
        if (!user) {
            return res.status(404).json({
                success: false,
                message: 'User not found'
            });
        }

        // Add coins and update referral count
        user.coins += coinsToAdd;
        user.successfulReferrals += 1;
        await user.save();

        res.json({
            success: true,
            message: 'Coins added successfully',
            data: {
                newCoins: user.coins,
                successfulReferrals: user.successfulReferrals
            }
        });
    } catch (error) {
        console.error('Add referral coins error:', error);
        res.status(500).json({
            success: false,
            message: 'Internal server error'
        });
    }
};

// Get all products
const getProducts = async (req, res) => {
    try {
        const { category, isActive = true } = req.query;
        
        let filter = { isActive };
        if (category) {
            filter.category = category;
        }

        const products = await Product.find(filter)
            .sort({ coinsRequired: 1 });

        res.json({
            success: true,
            data: products
        });
    } catch (error) {
        console.error('Get products error:', error);
        res.status(500).json({
            success: false,
            message: 'Internal server error'
        });
    }
};

// Get product by ID
const getProductById = async (req, res) => {
    try {
        const { productId } = req.params;
        
        const product = await Product.findById(productId);
        if (!product) {
            return res.status(404).json({
                success: false,
                message: 'Product not found'
            });
        }

        res.json({
            success: true,
            data: product
        });
    } catch (error) {
        console.error('Get product error:', error);
        res.status(500).json({
            success: false,
            message: 'Internal server error'
        });
    }
};

// Redeem product
const redeemProduct = async (req, res) => {
    try {
        const userId = req.user.id;
        const { productId, shippingAddress } = req.body;
        
        if (!productId || !shippingAddress) {
            return res.status(400).json({
                success: false,
                message: 'Product ID and shipping address are required'
            });
        }

        // Get user and product
        const user = await User.findById(userId);
        const product = await Product.findById(productId);
        
        if (!user || !product) {
            return res.status(404).json({
                success: false,
                message: 'User or product not found'
            });
        }

        if (!product.isActive) {
            return res.status(400).json({
                success: false,
                message: 'Product is not available'
            });
        }

        if (user.coins < product.coinsRequired) {
            return res.status(400).json({
                success: false,
                message: 'Insufficient coins'
            });
        }

        if (product.stock <= 0) {
            return res.status(400).json({
                success: false,
                message: 'Product out of stock'
            });
        }

        // Deduct coins and reduce stock
        user.coins -= product.coinsRequired;
        product.stock -= 1;
        
        await user.save();
        await product.save();

        // Create redemption record
        const redemption = new Redemption({
            user: userId,
            product: productId,
            coinsUsed: product.coinsRequired,
            shippingAddress: shippingAddress
        });

        await redemption.save();

        res.json({
            success: true,
            message: 'Product redeemed successfully',
            data: {
                redemptionId: redemption._id,
                remainingCoins: user.coins
            }
        });
    } catch (error) {
        console.error('Redeem product error:', error);
        res.status(500).json({
            success: false,
            message: 'Internal server error'
        });
    }
};

// Get user's redemptions
const getUserRedemptions = async (req, res) => {
    try {
        const userId = req.user.id;
        
        const redemptions = await Redemption.find({ user: userId })
            .populate('product', 'name imageUrl category')
            .sort({ createdAt: -1 });

        res.json({
            success: true,
            data: redemptions
        });
    } catch (error) {
        console.error('Get user redemptions error:', error);
        res.status(500).json({
            success: false,
            message: 'Internal server error'
        });
    }
};

module.exports = {
    getUserReferralStats,
    addReferralCoins,
    getProducts,
    getProductById,
    redeemProduct,
    getUserRedemptions
};
