const fs = require('fs');
const path = require('path');
const { v4: uuidv4 } = require('uuid');

const saveBase64Image = (base64String, subFolder = 'customers') => {
    if (!base64String || !base64String.startsWith('data:image')) {
        return base64String; // Return as is if not a base64 image (could be an existing path)
    }

    try {
        const matches = base64String.match(/^data:image\/([A-Za-z-+/]+);base64,(.+)$/);
        if (!matches || matches.length !== 3) {
            return base64String;
        }

        const extension = matches[1];
        const data = matches[2];
        const buffer = Buffer.from(data, 'base64');

        const fileName = `${uuidv4()}.${extension}`;
        const dir = path.join(__dirname, '../../uploads', subFolder);

        if (!fs.existsSync(dir)) {
            fs.mkdirSync(dir, { recursive: true });
        }

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

        return `/uploads/${subFolder}/${fileName}`;
    } catch (err) {
        console.error('Error saving image:', err);
        return base64String;
    }
};

module.exports = { saveBase64Image };
