#!/bin/bash

echo "🚀 Preparing for a forced build..."

# 1. Force Next.js to ignore ESLint and TypeScript errors during build
echo "⚙️ Updating Next.js configuration to bypass ESLint & TS checks..."

# Using Node.js to safely read, modify, and rewrite the next.config file (supports both .js and .mjs)
node -e "
const fs = require('fs');

const configFiles = ['next.config.js', 'next.config.mjs'];
let targetFile = null;

// Find the existing next config file
for (const file of configFiles) {
    if (fs.existsSync(file)) {
        targetFile = file;
        break;
    }
}

if (targetFile) {
    let content = fs.readFileSync(targetFile, 'utf8');
    
    // Check if eslint is already ignored
    if (!content.includes('ignoreDuringBuilds: true')) {
        // Simple regex replace to inject the overrides before the closing brace of the config object
        // This is a naive injection, but works for most standard next.config files
        content = content.replace(/(const\s+nextConfig\s*=\s*\{)/, '\$1\n  eslint: { ignoreDuringBuilds: true },\n  typescript: { ignoreBuildErrors: true },');
        fs.writeFileSync(targetFile, content);
        console.log('✅ Injected ignore rules into ' + targetFile);
    } else {
         console.log('ℹ️ Ignore rules already exist in ' + targetFile);
    }
} else {
    console.log('⚠️ No next.config.js or .mjs found. Creating next.config.mjs with ignore rules...');
    const defaultMjs = \`/** @type {import('next').NextConfig} */
const nextConfig = {
  eslint: {
    ignoreDuringBuilds: true,
  },
  typescript: {
    ignoreBuildErrors: true,
  },
};
export default nextConfig;
\`;
    fs.writeFileSync('next.config.mjs', defaultMjs);
}
"

# 2. Suppress Sentry warning (optional but cleans up output)
export SENTRY_SUPPRESS_GLOBAL_ERROR_HANDLER_FILE_WARNING=1

# 3. Run the build
echo "🏗️ Running bun run build..."
bun run build

echo "🎉 Build process finished!"
