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 !== 'GET') {
        return res.status(405).json({ success: false, error: 'Method not allowed' });
    }

    try {
        const isAuthenticated = await requireAuth(req, res);
        if (!isAuthenticated) return;
        const page = parseInt((req.query.page as string) || '1', 10) || 1;
        const limit = parseInt((req.query.limit as string) || '20', 10) || 20;
        const { items, total } = await MaterialService.getFavoritedMaterialsByUser(req.user!.id, page, limit);
        const hasNext = page * limit < total;

        return res.status(200).json({ success: true, data: { items, total, page, limit, hasNext }, timestamp: new Date().toISOString() });
    } catch (error: any) {
        console.error('Get user favorites error:', error);
        return res.status(500).json({ success: false, error: error.message || 'Failed to get favorites' });
    }
}
