import type { NextApiRequest, NextApiResponse } from 'next';
import { promises as fs } from 'fs';
import path from 'path';
import multer from 'multer';
import sharp from 'sharp';
import { createRouter } from 'next-connect';


// Generalized Multer configuration
const storage = multer.diskStorage({
    destination: (req, file, cb) => {
        const subfolder = req.query.subfolder ? decodeURIComponent(req.query.subfolder as string) : 'default';
        const uploadPath = path.join(process.cwd(), 'public/content', subfolder);

        fs.mkdir(uploadPath, { recursive: true })
            .then(() => cb(null, uploadPath))
            .catch(cb);
    },
    filename: (req, file, cb) => {
        const filename = decodeURIComponent(file.originalname);  // Ensure the filename is correctly decoded
        const prefix = req.body.prefix ? decodeURIComponent(req.body.prefix) : path.parse(filename).name;
        cb(null, `${prefix}${path.extname(filename)}`);
    }
});

const fileFilter = (req, file, cb) => {
    // Accept PDFs only
    if (file.mimetype === 'application/pdf') {
        cb(null, true);
    } else {
        cb(new Error('Only PDF files are allowed!'), false);
    }
};

const upload = multer({ storage, fileFilter });

const router = createRouter<NextApiRequest, NextApiResponse>();

router.use(upload.array('file'));

router.post((req, res) => {
    console.log(req.files);  // Log files to see if PDFs are included
    if (req.files.length === 0) {
        return res.status(400).json({ error: 'No files were uploaded.' });
    }
    // Process uploaded files, assume images are being resized and saved
    res.json({ message: 'Files uploaded successfully', files: req.files });
});

router.get(async (req, res) => {
    // Implement functionality to list files
    const directory = path.join(process.cwd(), 'public/content', req.query.subfolder as string);
    try {
        const files = await fs.readdir(directory);
        const imageUrls = files.map(file => `/content/${req.query.subfolder}/${file}`);
        res.json({ imageUrls });
    } catch (err) {
        res.status(500).json({ error: 'Internal Server Error', details: err.message });
    }
});

router.delete(async (req, res) => {
    // Implement functionality to delete a file
    const filePath = path.join(process.cwd(), 'public/content', req.query.subfolder as string, req.query.file as string);
    try {
        await fs.unlink(filePath);
        res.send('File deleted successfully.');
    } catch (error) {
        res.status(500).send('Failed to delete the file.');
    }
});

export default router.handler({
    onError: (err, req, res) => {
        console.error(err.stack);
        res.status(500).end('Something broke!');
    },
    onNoMatch: (req, res) => {
        res.status(404).end('Page is not found');
    }
});

export const config = {
    api: {
        bodyParser: false,
    },
};
