/* eslint-env node */
import * as fs from 'fs';
import replace from 'rollup-plugin-replace';
import lwc from '@lwc/rollup-plugin';
import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import moduleAlias from 'rollup-plugin-alias';
import { terser } from 'rollup-plugin-terser';
import proxyCompat from 'rollup-plugin-compat';

import { getOutputConfigs } from '@webruntime/common';
import { resourceHash, codeSize } from '@webruntime/rollup-plugins';

const COMPAT_MODULES_ALIAS = {
    '@babel/runtime': 'TalonCompat.babel',
    'proxy-compat': 'Proxy',
};

const TALON_COMPAT_SRC = fs.readFileSync(`dist/compat.js`, 'utf8');

/**
 * Consider the compat helpers as external since they'll be included
 * as part of compat.js generated by rollup.config.compat.js.
 */
function external(id) {
    return !!Object.keys(COMPAT_MODULES_ALIAS).find(prefix => id.startsWith(`${prefix}/`));
}

/**
 * Map external compat helpers to the corresponding global variables.
 */
function globals(id) {
    for (const [prefix, alias] of Object.entries(COMPAT_MODULES_ALIAS)) {
        const [, name] = id.split(`${prefix}/`);
        if (name) {
            return `${alias}.${name.replace('/', '.')}`;
        }
    }
    return null;
}

/**
 * Include compat.js source when applicable
 */
function talonCompat() {
    return {
        renderChunk(code) {
            return TALON_COMPAT_SRC + code;
        },
    };
}

function getConfig({ mode, minify, target, env }) {
    const isCompat = target === 'es5';
    const plugins = [
        resourceHash({ mode, resourceDescriptor: 'framework://talon' }),
        lwc({ resolveFromPackages: true, exclude: ['/**/*.mjs'] }),
        moduleAlias({
            lwc: require.resolve('@lwc/engine/dist/modules/es2017/engine.js'),
            'forceChatterApi/util': require.resolve(
                '@talon/connect-gen/dist/forceChatterApi/util/util.js'
            ),
            'wire-service': require.resolve('@lwc/wire-service/dist/modules/es2017/wire.js'),
            transport: 'src/modules/talon/transport/transport.js',
        }),
        replace({
            'process.env.NODE_ENV': JSON.stringify(env),
            'process.env.LWC_TARGET': JSON.stringify(target),
        }),
        resolve(),
        commonjs(),
        isCompat && proxyCompat({ polyfills: false }),
        isCompat && talonCompat(),
        minify && terser(),
        codeSize(),
    ];

    return {
        input: 'src/index.js',
        external,
        output: {
            file: `talon.js (${mode})`,
            format: 'iife',
            name: 'Talon',
            globals,
            sourcemap: mode === 'dev' ? 'inline' : false,
        },
        plugins,
    };
}

const modes = process.env.MODE && process.env.MODE.split(',');

export default getOutputConfigs(modes).map(getConfig);
