import { compile } from '@mdx-js/mdx';
import fs from 'node:fs';
import path from 'node:path';
import matter from 'gray-matter';

const TARGET_DIRS = ['./data/blog', './data/products'];

function getAllFiles(dirPath, arrayOfFiles) {
    if (!fs.existsSync(dirPath)) return arrayOfFiles || [];

    const files = fs.readdirSync(dirPath);

    arrayOfFiles = arrayOfFiles || [];

    files.forEach(function (file) {
        const fullPath = path.join(dirPath, file);
        if (fs.statSync(fullPath).isDirectory()) {
            arrayOfFiles = getAllFiles(fullPath, arrayOfFiles);
        } else {
            arrayOfFiles.push(fullPath);
        }
    });

    return arrayOfFiles;
}

const allMdxFiles = TARGET_DIRS.flatMap(dir => getAllFiles(dir)).filter(file => file.endsWith('.mdx'));

console.log(`Found ${allMdxFiles.length} MDX files to validate...`);

let errorCount = 0;

for (const file of allMdxFiles) {
    const fileContent = fs.readFileSync(file, 'utf8');
    const { content } = matter(fileContent);

    try {
        // Attempt to compile MDX content
        await compile(content);
    } catch (err) {
        console.error(`\x1b[31mError in ${file}:\x1b[0m`);
        console.error(err.message);
        if (err.line && err.column) {
            console.error(`At line ${err.line}, column ${err.column}`);
        }
        errorCount++;
    }
}

if (errorCount > 0) {
    console.error(`\n\x1b[31mValidation failed: ${errorCount} errors found.\x1b[0m`);
    process.exit(1);
} else {
    console.log('\n\x1b[32mAll MDX files are valid.\x1b[0m');
}
