// @ts-check
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const path = require("path");
const { merge } = require("webpack-merge");
const yaml = require("yaml");
const {
  kemonoSite,
  apiServerBaseURL,
  apiServerPort,
} = require("./configs/vars.mjs");
const baseConfig = require("./webpack.config");

const projectPath = path.resolve(__dirname, "src");

/**
 * @type {import("webpack-dev-server").Configuration}
 */
const devServer = {
  host: "0.0.0.0",
  port: 3450,
  proxy: [
    {
      context: ["/api","/icons","/data", "/thumbnail"],
      target: `localhost:3449`,
    },
  ],
  static: {
    directory: path.resolve(__dirname, "static"),
    watch: true,
  },
  hot: true,
  // liveReload: true,
  client: {
    overlay: true,
    progress: true,
  },
  historyApiFallback: {
    index: "/index.html",
  },
};

/**
 * @type import("webpack").Configuration
 */
const webpackConfigDev = {
  mode: "development",
  devtool: "inline-source-map",
  devServer: devServer,
  plugins: [
    new MiniCssExtractPlugin({
      filename: "static/bundle/css/[name].css",
      chunkFilename: "static/bundle/css/[id].chunk.css",
    }),
  ],
  module: {
    parser: {
      javascript: {
        exportsPresence: "error",
      },
    },
    rules: [
      {
        test: /\.tsx?$/,
        use: "ts-loader",
        exclude: /node_modules/,
      },
      {
        test: /\.s[ac]ss$/i,
        use: [
          "style-loader",
          {
            loader: "css-loader",
            options: {
              sourceMap: true,
            },
          },
          {
            loader: "sass-loader",
            options: {
              sourceMap: true,
              // TODO: find how to prepend data properly
              additionalData: `$kemono-site: '${kemonoSite}';`,
            },
          },
        ],
      },
      {
        test: /\.(png|jpg|jpeg|gif|webp)$/i,
        type: "asset/resource",
      },
      {
        test: /\.(woff|woff2|eot|ttf|otf)$/i,
        type: "asset/resource",
      },
      {
        test: /\.svg$/i,
        type: "asset/resource",
      },
      {
        test: /\.css$/,
        use: ["style-loader", "css-loader"],
      },
      {
        test: /\.yaml$/i,
        type: "json",
        parser: {
          parse: yaml.parse,
        },
      },
    ],
  },
  output: {
    path: path.resolve(__dirname, "dev"),
    filename: "static/bundle/js/[name].bundle.js",
    assetModuleFilename: "static/bundle/assets/[name][ext][query]",
    publicPath: "/",
  },
};

module.exports = merge(baseConfig, webpackConfigDev);
