// Validation middleware for request data
function validateRequest(schema) {
    return (req, res, next) => {
        const { error } = schema(req.body);

        if (error) {
            return res.status(400).json({
                error: 'Validation failed',
                details: error.details || error.message
            });
        }

        next();
    };
}

// Validation schemas
const schemas = {
    // Order creation validation
    createOrder: (data) => {
        if (!data.items || !Array.isArray(data.items) || data.items.length === 0) {
            return { error: { message: 'Order must contain at least one item' } };
        }

        if (!data.payment_method) {
            return { error: { message: 'Payment method is required' } };
        }

        for (const item of data.items) {
            if (!item.food_id || !item.quantity || item.quantity < 1) {
                return { error: { message: 'Invalid item in order' } };
            }
        }

        return {};
    },

    // Food item validation
    createFoodItem: (data) => {
        if (!data.name || data.name.trim().length === 0) {
            return { error: { message: 'Food name is required' } };
        }

        if (!data.category || !['breakfast', 'lunch', 'snacks', 'beverages'].includes(data.category)) {
            return { error: { message: 'Invalid category' } };
        }

        if (!data.price || data.price <= 0) {
            return { error: { message: 'Valid price is required' } };
        }

        return {};
    },

    // Payment details validation
    savePayment: (data) => {
        if (!data.payment_method) {
            return { error: { message: 'Payment method is required' } };
        }

        if (!data.name || data.name.trim().length === 0) {
            return { error: { message: 'Name is required' } };
        }

        if (!data.mobile || !/^\d{10}$/.test(data.mobile)) {
            return { error: { message: 'Valid 10-digit mobile number is required' } };
        }

        return {};
    },

    // Student registration validation
    registerStudent: (data) => {
        if (!data.student_id || data.student_id.trim().length === 0) {
            return { error: { message: 'Student ID is required' } };
        }

        if (!data.name || data.name.trim().length === 0) {
            return { error: { message: 'Name is required' } };
        }

        return {};
    }
};

module.exports = { validateRequest, schemas };
