import babel from "@rollup/plugin-babel";
import nodeResolve from "@rollup/plugin-node-resolve";
import commonjs from "@rollup/plugin-commonjs";
import terser from "@rollup/plugin-terser";
import Path from "path";
import fs from "fs";

const changeVersion = () => {
    const version = fs.readFileSync(".version", { encoding: "utf8" }) || "1.0.0";
    let versionNumber = parseInt(version.replace(/\./g, ''));
    versionNumber += 1;
    const newVersion = versionNumber.toString().split('').join('.');
    fs.writeFileSync(".version", newVersion);
    return newVersion;
}
const changeManifest = (others = {}) => {
    let manifest = JSON.parse(fs.readFileSync("manifest.json", { encoding: "utf8" }));
    manifest = {...manifest, version: changeVersion(), ...others}
    fs.writeFileSync("dist/manifest.json", JSON.stringify(manifest));
}
const inputs = ["src/main.js", "src/popup.js", "src/background.js"];
const conf = [];
const nodeEnv = process.env.NODE_ENV?.trim() || 'DEV';
console.log(`NODE_ENV: ${nodeEnv}`);
nodeEnv == 'TEST' ? changeManifest({ name: 'Test' }) : changeManifest();
inputs.forEach(input => {
    const fn = Path.parse(input).name;
    if (process.env.NODE_ENV == 'PROD') {
        conf.push({
            input,
            output: {
                file: `dist/js/${fn}.min.js`,
                format: "umd",
                name: "G",
                sourcemap: true
            },
            plugins: [
                nodeResolve({
                    browser: true,
                }),
                commonjs({
                    include: /node_modules/,
                    requireReturnsDefault: "auto",
                }),
                babel({
                    babelHelpers: "bundled",
                }),
                terser()
            ]
        });
    }
    conf.push({
        input,
        output: {
            file: `dist/js/${fn}.js`,
            format: "iife",
            name: "G",
        },
        plugins: [
            nodeResolve({
                browser: true,
            }),
            commonjs(),
        ]
    });
});
export default conf;