import path from 'path';
import fs from 'fs';
import { fileURLToPath } from 'url';
import { safeError } from '../utils/errorHandler.js';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const rootPath = path.join(__dirname, '..', '..');

export class UploadController {
    static async uploadBase64(req, res) {
        try {
            const { image, folder, fileName } = req.body;
            if (!image || !folder || !fileName) {
                return res.status(400).json({ error: 'Missing image data, folder, or fileName' });
            }

            const base64Data = image.replace(/^data:image\/\w+;base64,/, "");
            const buffer = Buffer.from(base64Data, 'base64');

            const targetDir = path.join(rootPath, 'public', 'materials', folder);
            
            if (!fs.existsSync(targetDir)) {
                fs.mkdirSync(targetDir, { recursive: true });
            }

            const filePath = path.join(targetDir, fileName);
            fs.writeFileSync(filePath, buffer);

            res.json({ url: `/materials/${folder}/${fileName}` });
        } catch (error) {
            safeError(res, error);
        }
    }
}
