import { NextApiResponse } from 'next';
import { AuthenticatedRequest, requireAuth } from '../../../../../lib/middleware/authMiddleware';
import { MaterialService } from '../../../../../backend/services/materialService';

export default async function handler(req: AuthenticatedRequest, res: NextApiResponse) {
    if (req.method !== 'POST') {
        return res.status(405).json({ success: false, error: 'Method not allowed' });
    }

    // Require authentication
    const isAuthenticated = await requireAuth(req, res);
    if (!isAuthenticated) {
        return;
    }

    const { id } = req.query;

    if (typeof id !== 'string') {
        return res.status(400).json({ success: false, error: 'Invalid material ID' });
    }

    try {
        const newFavoriteCount = await MaterialService.toggleFavorite(id, req.user!.id);
        return res.status(200).json({ success: true, data: { favorites: newFavoriteCount } });
    } catch (error) {
        console.error('Error toggling favorite:', error);
        return res.status(500).json({ success: false, error: 'Failed to toggle favorite' });
    }
}
