import { NextApiRequest, NextApiResponse } from 'next';
import { ref, uploadBytes, getDownloadURL } from 'firebase/storage';
import { IncomingForm, Files, Fields } from 'formidable';
import { promises as fs } from 'fs';
import { withIronSessionApiRoute } from 'iron-session/next';
import { storage } from '@/firebase';
import { sessionOptions } from '@/lib/session';
import { v4 } from 'uuid';

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

export default withIronSessionApiRoute(handler, sessionOptions);

export async function handler(req: NextApiRequest, res: NextApiResponse) {
    if (!req.session.user) {
        res.status(401).json({ error: 'Not authorized' });
        return;
    }

    if (req.method !== 'POST') {
        return res.status(405).json({ error: 'Not allowed' });
    }

    const directory = (req.query.directory as string) || "uploads";

    try {
        const form = new IncomingForm({
            keepExtensions: true,
            multiples: true,
        });

        const [fields, files]: [Fields, Files] = await new Promise((resolve, reject) => {
            form.parse(req, (err, fields, files) => {
                if (err) reject(err);
                resolve([fields, files]);
            });
        });

        const fileArray = files.file;
        if (!fileArray) {
            return res.status(400).json({ error: 'No files provided' });
        }

        const filesToProcess = Array.isArray(fileArray) ? fileArray : [fileArray];

        const uploadPromises = filesToProcess.map(async (file) => {
            const split = file.originalFilename?.split('.') || ["bin"];
            const extension = split[split.length - 1];

            const buffer = await fs.readFile(file.filepath);
            const storageRef = ref(storage, `${directory}/${v4()}.${extension}`);
            await uploadBytes(storageRef, buffer);
            const downloadURL = await getDownloadURL(storageRef);
            await fs.unlink(file.filepath);
            return downloadURL;
        });

        const urls = await Promise.all(uploadPromises);
        res.status(200).json({ urls });
    } catch (error) {
        console.error('Upload error:', error);
        res.status(500).json({ error: 'Upload failed' });
    }
}