/**
 * esbuild bundler config file with TypeScript and Tailwind CSS support
 * Enhanced for APIDoc 4.0 with better development experience
 * - Entry point set at runtime
 * - File output set at runtime
 * - Define is set at runtime
 * - minify overridden at runtime, based on debug flag
 * - sourcemap overridden at runtime, based on debug flag
 */
const postcss = require('esbuild-postcss');
const path = require('path');
const fs = require('fs');

const tailwindConfigPath = path.join(__dirname, '..', '..', 'tailwind.config.js');

// Debug: Check config loading
try {
  const config = require(tailwindConfigPath);
  console.log('✓ TailwindCSS config loaded successfully');
  console.log('Content paths detected:', config.content?.length || 0, 'paths');
  if (config.content && config.content.length > 0) {
    config.content.forEach((contentPath, index) => {
      console.log(`  [${index}]: ${contentPath}`);

      // Check if paths contain files
      const glob = require('glob');
      try {
        const files = glob.globSync(contentPath);
        console.log(`    Found ${files.length} files matching this pattern`);
        if (files.length > 0) {
          console.log(`    Sample files: ${files.slice(0, 3).join(', ')}${files.length > 3 ? '...' : ''}`);
        }
      } catch (globErr) {
        console.log(`    Error checking files: ${globErr.message}`);
      }
    });
  }
} catch (err) {
  console.error('✗ Error loading TailwindCSS config:', err.message);
}

module.exports = {
  bundle: true,
  minify: true,
  sourcemap: false,
  resolveExtensions: ['.ts', '.tsx', '.js', '.jsx', '.mjs'],
  conditions: ['style'],
  loader: {
    '.js': 'jsx',
    '.jsx': 'jsx',
    '.ts': 'ts',
    '.tsx': 'tsx',
    '.css': 'css',
    '.eot': 'dataurl',
    '.svg': 'dataurl',
    '.ttf': 'dataurl',
    '.woff': 'dataurl',
    '.woff2': 'dataurl'
  },
  plugins: [
    postcss({
      plugins: [
        require('@tailwindcss/postcss')({
          config: tailwindConfigPath
        }),
        require('autoprefixer'),
      ]
    })
  ],
  target: 'es2022',
  alias: {
    '@': './template/src',
    '@types': '../src/types'
  },
  banner: {
    js: '/* APIDoc 4.0 Template - Generated with TypeScript support */'
  },
  define: {
    'process.env.NODE_ENV': '"production"'
  },
  format: 'iife',
  globalName: 'ApiDoc'
};
