const path = require('path');

const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const { GenerateSW } = require('workbox-webpack-plugin');
const HtmlWebpackPlugin = require("html-webpack-plugin")
const Webpack = require('webpack');

const config = {
    entry: {
        main: ['./src/index.tsx'],
    },
    output: {
        path: path.resolve('./build/'),
    },
    resolve: {
        extensions: ['.tsx', '.ts', '.js'],
        alias: {
            '@': path.resolve(__dirname, './src'),
        }
    },
    module: {
        rules: [{
            test: /\.s[ac]ss$/,
            use: ["style-loader", "css-loader?sourceMap", "sass-loader?sourceMap"]
        }, {
            test: /\.css$/,
            use: ["style-loader", "css-loader"]
        }, {
            test: /\.tsx?$/,
            use: 'babel-loader',
            exclude: /node_modules/
        }, {
            test: /\.(png|svg|jpg|gif)$/,
            use: 'file-loader',
        }, {
            test: /\.(woff|woff2|eot|ttf|otf)$/,
            use: 'file-loader'
        }, {
            test: /\.ya?ml$/,
            type: 'json',
            use: 'yaml-loader'
        }]
    },
    plugins: [
        new CleanWebpackPlugin(),
        new HtmlWebpackPlugin({  // Also generate a test.html
            filename: 'index.html',
            template: 'public/index.html'
        }),
        new Webpack.EnvironmentPlugin(['API_BASE_URL'])
    ],
    devServer: {
        contentBase: path.resolve("./public/"),
        host: process.env.APP_HOST || 'system-praktyk-front.localhost',
        disableHostCheck: true,
        historyApiFallback: true,
        overlay: true,
        https: !!process.env.APP_HTTPS || false,
        port: parseInt(process.env.APP_PORT || "3000"),
        proxy: {
            "/api": {
                target: "https://system-praktyk.dev.kadet.net/api/",
                changeOrigin: true,
                pathRewrite: {
                    "^/api": ''
                }
            }
        }
    },
    optimization: {
        usedExports: true
    }
};

module.exports = (env, argv) => {
    if (argv.mode === 'development') {
        config.devtool = 'inline-source-map';
    }

    process.env.BABEL_ENV = argv.mode || 'production';

    return config;
};