import { loadConfig, optimize } from 'svgo';
import fs from 'fs';

let lastContent = null;
const config = await loadConfig();

export default function svgoPlugin() {
    return {
        name: 'svgo',
        watchChange(path, change) {
            // If 'path' does not contain 'assets/icons' with a .svg extension, return
            if (!path.includes('assets/icons') || !path.includes('.svg')) return;

            // Get file content
            const content = fs.readFileSync(path, 'utf8');

            // If the content is the same as the last content, return
            if (content === lastContent) return;

            try {
                const result = optimize(content, config);

                // Write the optimized SVG to the file
                fs.writeFileSync(path, result.data, 'utf8');

                // Log the change
                console.log(`Optimized SVG: ${path}`);

                // Update the last change
                lastContent = content;
            } catch (error) {
                console.log(`Error optimizing SVG: ${path}: ${error}`);
            }
        }
    };
}
