import {join, dirname} from "node:path";
import {test, expect, jest} from "@jest/globals";

// Rollup * plugins
import { rollup } from "rollup";
import urlPlugin from "@rollup/plugin-url";
import nodeResolve from "@rollup/plugin-node-resolve";
import babelPlugin from "@rollup/plugin-babel";
import commonJsPlugin from "@rollup/plugin-commonjs";
import typescriptPlugin from "@rollup/plugin-typescript";
import replacePlugin from "@rollup/plugin-replace";

import html from "../../src/index.ts";
import {runBrowserTest} from "../util/browser-test.ts";

import {fileURLToPath} from "node:url";
import handlebars from "handlebars";
// import {debugPrintOutput, getCode, runBrowserTest} from "../util/index.ts";
const __dirname = dirname(fileURLToPath(import.meta.url));
process.chdir(join(__dirname, 'fixtures'));


const defaultAssetInclude = [
    '**/*.(png|jpg|jpeg|gif|ico|svg)',// images, svg
    '**/*.(woff|woff2|eot|ttf|otf)',// fonts
    '**/*.(webm|mp4)',// video
];


jest.setTimeout(30*1000);// Bundling react + typescript is getting heavy
test('web-bundle', async () => {
    const out = await runBrowserTest({
        input: 'index.hbs',
        treeshake: 'smallest',
        plugins: [
            html({
                transform(src) {
                    return handlebars.compile(src)({
                        head: `<title>I'm cool!</title>`
                    });
                }
            }),
            nodeResolve({
                extensions: ['.js', '.mjs', '.jsx', '.ts', '.tsx'],
                browser: true,
            }),
            commonJsPlugin({
            }),
            typescriptPlugin({
                sourceMap: true,
                // exclude: 'node_modules/**',
                noEmitOnError: true,
                outputToFilesystem: false,
                noForceEmit: true,
                jsx: "preserve",
            }),
            babelPlugin({
                extensions: ['.js', '.mjs', '.jsx', '.ts', '.tsx'],
                babelHelpers: "bundled",
            }),
            replacePlugin({
                preventAssignment: false,
                'process.env.NODE_ENV': process.env.NODE_ENV==='production'?`'${process.env.NODE_ENV}'` : '"development"'
            }),

            urlPlugin({
                include: defaultAssetInclude,
            }),
        ],
    }, {
        path: 'index.html'
    },{
        dir: 'output', // Output all files
        format: 'es', //  iifi and cjs should be added to tests
        sourcemap: true,// Test if #sourcemapUrl is not accidentally included in the html-output
        chunkFileNames: '[name].js',
        entryFileNames: '[name].[extname]',
        assetFileNames: '[name].[extname]',
    });
    expect(out).toMatchSnapshot();

    // const code = await getCode(bundle, output);
    // debugPrintOutput('jsx-web-app',code);
});

