const express = require('express');
const router = express.Router();
const { supabaseAdmin } = require('../config/supabase');
const { authenticateUser, requireRole } = require('../middleware/auth');
const { validateRequest, schemas } = require('../middleware/validation');
const multer = require('multer');
const path = require('path');

// Configure multer for file uploads
const storage = multer.memoryStorage();
const upload = multer({
    storage,
    limits: { fileSize: 5 * 1024 * 1024 }, // 5MB limit
    fileFilter: (req, file, cb) => {
        const allowedTypes = /jpeg|jpg|png|webp/;
        const extname = allowedTypes.test(path.extname(file.originalname).toLowerCase());
        const mimetype = allowedTypes.test(file.mimetype);

        if (extname && mimetype) {
            cb(null, true);
        } else {
            cb(new Error('Only image files are allowed'));
        }
    }
});

// Get all menu items (with optional category filter)
router.get('/', async (req, res) => {
    try {
        const { category, available } = req.query;

        let query = supabaseAdmin.from('food_items').select('*');

        if (category) {
            query = query.eq('category', category);
        }

        if (available === 'true') {
            query = query.eq('availability', 'available');
        }

        query = query.order('category').order('name');

        const { data, error } = await query;

        if (error) throw error;

        res.json({ success: true, items: data });
    } catch (error) {
        console.error('Get menu error:', error);
        res.status(500).json({ error: 'Failed to fetch menu items' });
    }
});

// Get single menu item
router.get('/:id', async (req, res) => {
    try {
        const { data, error } = await supabaseAdmin
            .from('food_items')
            .select('*')
            .eq('id', req.params.id)
            .single();

        if (error) throw error;

        if (!data) {
            return res.status(404).json({ error: 'Food item not found' });
        }

        res.json({ success: true, item: data });
    } catch (error) {
        console.error('Get food item error:', error);
        res.status(500).json({ error: 'Failed to fetch food item' });
    }
});

// Create new menu item (kitchen/admin only)
router.post('/', authenticateUser, requireRole('kitchen', 'admin'), validateRequest(schemas.createFoodItem), async (req, res) => {
    try {
        const { name, category, price, description, prep_time, availability } = req.body;

        const { data, error } = await supabaseAdmin
            .from('food_items')
            .insert({
                name,
                category,
                price,
                description,
                prep_time: prep_time || 15,
                availability: availability || 'available'
            })
            .select()
            .single();

        if (error) throw error;

        res.json({ success: true, item: data });
    } catch (error) {
        console.error('Create food item error:', error);
        res.status(500).json({ error: 'Failed to create food item' });
    }
});

// Update menu item (kitchen/admin only)
router.put('/:id', authenticateUser, requireRole('kitchen', 'admin'), async (req, res) => {
    try {
        const { name, category, price, description, prep_time, availability } = req.body;

        const updateData = {};
        if (name) updateData.name = name;
        if (category) updateData.category = category;
        if (price !== undefined) updateData.price = price;
        if (description !== undefined) updateData.description = description;
        if (prep_time !== undefined) updateData.prep_time = prep_time;
        if (availability) updateData.availability = availability;
        updateData.updated_at = new Date().toISOString();

        const { data, error } = await supabaseAdmin
            .from('food_items')
            .update(updateData)
            .eq('id', req.params.id)
            .select()
            .single();

        if (error) throw error;

        res.json({ success: true, item: data });
    } catch (error) {
        console.error('Update food item error:', error);
        res.status(500).json({ error: 'Failed to update food item' });
    }
});

// Upload food image (kitchen/admin only)
router.post('/:id/image', authenticateUser, requireRole('kitchen', 'admin'), upload.single('image'), async (req, res) => {
    try {
        if (!req.file) {
            return res.status(400).json({ error: 'No image file provided' });
        }

        const foodId = req.params.id;
        const fileName = `${foodId}-${Date.now()}${path.extname(req.file.originalname)}`;

        // Upload to Supabase Storage
        // Ensure bucket exists
        const { data: buckets } = await supabaseAdmin.storage.listBuckets();
        const bucketExists = buckets?.find(b => b.name === 'food-images');

        if (!bucketExists) {
            await supabaseAdmin.storage.createBucket('food-images', {
                public: true
            });
        }

        const { data: uploadData, error: uploadError } = await supabaseAdmin.storage
            .from('food-images')
            .upload(fileName, req.file.buffer, {
                contentType: req.file.mimetype,
                upsert: true
            });

        if (uploadError) throw uploadError;

        // Get public URL
        const { data: { publicUrl } } = supabaseAdmin.storage
            .from('food-images')
            .getPublicUrl(fileName);

        // Update food item with image URL
        const { data, error } = await supabaseAdmin
            .from('food_items')
            .update({ image_url: publicUrl, updated_at: new Date().toISOString() })
            .eq('id', foodId)
            .select()
            .single();

        if (error) throw error;

        res.json({ success: true, item: data, image_url: publicUrl });
    } catch (error) {
        console.error('Upload image error:', error);
        res.status(500).json({ error: 'Failed to upload image' });
    }
});

// Delete menu item (admin only)
router.delete('/:id', authenticateUser, requireRole('admin'), async (req, res) => {
    try {
        const { error } = await supabaseAdmin
            .from('food_items')
            .delete()
            .eq('id', req.params.id);

        if (error) throw error;

        res.json({ success: true });
    } catch (error) {
        console.error('Delete food item error:', error);
        res.status(500).json({ error: 'Failed to delete food item' });
    }
});

module.exports = router;
