import fs from 'fs';
import path from 'path';

/**
 * Decodes a Base64 string and saves it as a file.
 * @param base64Data The Base64 string (data URL).
 * @param uploadDir The directory to save the file (relative to process.cwd()).
 * @returns The relative path to the saved file, or the original string if not Base64.
 */
export const saveBase64Image = (base64Data: string, uploadDir: string = 'uploads'): string => {
    // Regular expression to check if the string is a Base64 data URL
    const matches = base64Data.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/);

    if (!matches || matches.length !== 3) {
        // Not a Base64 data URL, return as is (might be an existing file path)
        return base64Data;
    }

    const type = matches[1]; // e.g., 'image/png'
    const data = matches[2];
    const buffer = Buffer.from(data, 'base64');

    // Extract extension from mime type
    const extension = type.split('/')[1];
    // Basic mapping for common types if needed, but split usually works for png/jpeg

    // Generate unique filename
    const filename = `question_${Date.now()}_${Math.floor(Math.random() * 1000)}.${extension}`;

    // Ensure directory exists
    const fullPath = path.join(process.cwd(), uploadDir);
    if (!fs.existsSync(fullPath)) {
        fs.mkdirSync(fullPath, { recursive: true });
    }

    // Write file
    fs.writeFileSync(path.join(fullPath, filename), buffer);

    // Return relative path (using forward slashes for compatibility)
    return `${uploadDir}/${filename}`;
};
