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

export default async function handler(req: AuthenticatedRequest, res: NextApiResponse) {
    // GET: List materials
    if (req.method === 'GET') {
        // Optional auth - attach user if logged in
        await optionalAuth(req);

        try {
            const type = req.query.type as any;
            const page = parseInt((req.query.page as string) || '1', 10) || 1;
            const limit = parseInt((req.query.limit as string) || '20', 10) || 20;
            const q = (req.query.q as string) || '';
            const { items, total } = await MaterialService.getAllMaterials(type, page, limit, q);
            const hasNext = page * limit < total;
            return res.status(200).json({ success: true, data: { items, total, page, limit, hasNext } });
        } catch (error) {
            console.error('Error fetching materials:', error);
            return res.status(500).json({ success: false, error: 'Failed to fetch materials' });
        }
    }

    // POST: Create material
    if (req.method === 'POST') {
        // Require authentication
        const isAuthenticated = await requireAuth(req, res);
        if (!isAuthenticated) {
            return; // requireAuth already sent the response
        }

        try {
            const newMaterial = await MaterialService.createMaterial(req.user!.id, req.body);
            return res.status(201).json({ success: true, data: newMaterial });
        } catch (error) {
            console.error('Error creating material:', error);
            return res.status(500).json({ success: false, error: 'Failed to create material' });
        }
    }

    return res.status(405).json({ success: false, error: 'Method not allowed' });
}
