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

export default async function handler(req: AuthenticatedRequest, res: NextApiResponse) {
    const { id } = req.query;

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

    // GET: Get material by ID
    if (req.method === 'GET') {
        // Optional auth
        await optionalAuth(req);

        try {
            const material = await MaterialService.getMaterialById(id);

            if (!material) {
                return res.status(404).json({ success: false, error: 'Material not found' });
            }

            return res.status(200).json({ success: true, data: material });
        } catch (error) {
            console.error('Error fetching material:', error);
            return res.status(500).json({ success: false, error: 'Failed to fetch material' });
        }
    }

    // DELETE: Delete material
    if (req.method === 'DELETE') {
        // Require authentication
        const isAuthenticated = await requireAuth(req, res);
        if (!isAuthenticated) {
            return;
        }

        try {
            // Get material to check authorization
            const material = await MaterialService.getMaterialById(id);

            if (!material) {
                return res.status(404).json({ success: false, error: 'Material not found' });
            }

            // Check if user is author or admin
            if (material.author.id !== req.user!.id && req.user!.role !== UserRole.ADMIN) {
                return res.status(403).json({ success: false, error: 'Not authorized to delete this material' });
            }

            await MaterialService.deleteMaterial(id);
            return res.status(200).json({ success: true, message: 'Material deleted successfully' });
        } catch (error) {
            console.error('Error deleting material:', error);
            return res.status(500).json({ success: false, error: 'Failed to delete material' });
        }
    }

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