/* eslint-env node */

import * as webpack from 'webpack';
import * as path from 'path';
import { ConsoleRemotePlugin } from "@openshift-console/dynamic-plugin-sdk-webpack";
import CopyWebpackPlugin from 'copy-webpack-plugin';
import { Configuration as WebpackConfiguration } from "webpack";
import { Configuration as WebpackDevServerConfiguration } from "webpack-dev-server";

interface Configuration extends WebpackConfiguration {
  devServer?: WebpackDevServerConfiguration;
}

const isProd = process.env.NODE_ENV === "production";

const config: Configuration = {
  mode: isProd ? "production" : "development",
  entry: {
    'project-pause-plugin': path.resolve(__dirname, 'src', 'index.ts')
  },
  context: path.resolve(__dirname, "src"),
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].js',
    publicPath: "auto",
    chunkFormat: 'module',
  },
  resolve: {
    extensions: [".ts", ".tsx", ".js", ".jsx"],
  },
  module: {
    rules: [
      {
        test: /\.(jsx?|tsx?)$/,
        exclude: /\/node_modules\//,
        use: [
          {
            loader: "ts-loader",
            options: {
              configFile: path.resolve(__dirname, "tsconfig.json"),
            },
          },
        ],
      },
      {
        test: /\.(css)$/,
        use: ["style-loader", "css-loader"],
      },
      {
        test: /\.(png|jpg|jpeg|gif|svg|woff2?|ttf|eot|otf)(\?.*$|$)/,
        type: "asset/resource",
        generator: {
          filename: "assets/[name][ext]",
        },
      },
    ],
  },
  plugins: [
    new ConsoleRemotePlugin({
      pluginMetadata: {
        name: "project-pause-plugin",
        version: "0.0.1",
        displayName: "Project Pause Plugin",
        description: "Adds ability to pause and resume projects",
        exposedModules: {
          projectActions: "./components/project-actions",
        },
      },
      extensions: [
        {
          type: "console.action/provider",
          properties: {
            contextId: "namespace-overview-actions",
            provider: {
              $codeRef: "projectActions.PauseProjectAction",
            },
          },
        },
      ]
    }),
    new CopyWebpackPlugin({
      patterns: [
        { 
          from: path.resolve(__dirname, 'src/locales'),
          to: 'locales'
        }
      ]
    }),
  ],
  devServer: {
    static: "./dist",
    port: 9001,
    allowedHosts: "all",
    headers: {
      "Access-Control-Allow-Origin": "*",
      "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS",
      "Access-Control-Allow-Headers": "X-Requested-With, Content-Type, Authorization",
      "Content-Security-Policy": "default-src 'self'; script-src 'self' 'unsafe-eval' 'unsafe-inline';"
    },
    devMiddleware: {
      writeToDisk: true,
    },
  },
  devtool: isProd ? false : "source-map",
  optimization: {
    chunkIds: "named",
    minimize: isProd,
  },
};

export default config;
