/**
 * electron-builder afterPack hook
 * Removes "type": "module" from the packaged package.json
 * to ensure CommonJS files work correctly in the Electron app.
 */

const fs = require('fs')
const path = require('path')

exports.default = async function (context) {
    const appDir = context.appOutDir
    const resourcesPath = path.join(appDir, 'resources', 'app')
    const packageJsonPath = path.join(resourcesPath, 'package.json')

    console.log('afterPack: Checking for package.json at:', packageJsonPath)

    if (fs.existsSync(packageJsonPath)) {
        const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'))

        // Remove the "type": "module" field to ensure CommonJS compat
        if (packageJson.type === 'module') {
            delete packageJson.type
            fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2))
            console.log('afterPack: Removed "type": "module" from package.json')
        }
    } else {
        console.log('afterPack: package.json not found, skipping...')
    }
}
