import CopyPlugin from "copy-webpack-plugin";
import MiniCssExtractPlugin from "mini-css-extract-plugin";
import path from "node:path";
import { fileURLToPath } from "url";
import webpack from "webpack";
import packageInfo from "./package.json" with { type: "json" };

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const config: webpack.Configuration = {
  target: ["web", "es6"],
  entry: ["./src/index.ts", "./src/main.scss"],
  module: {
    rules: [
      { test: /\.svg$/, use: ["file-loader"] },
      {
        test: /\.tsx?$/,
        use: [{ loader: "babel-loader" }, { loader: "ts-loader" }],
        exclude: /node_modules/,
      },
      {
        test: /\.s[ac]ss$/i,
        use: [
          MiniCssExtractPlugin.loader,
          { loader: "css-loader", options: { sourceMap: false, url: false } },
          { loader: "postcss-loader", options: { sourceMap: false } },
          {
            loader: "sass-loader",
            options: {
              sourceMap: false,
              sassOptions: { quietDeps: true, silenceDeprecations: ["color-functions", "global-builtin", "import"] },
            },
          },
        ],
      },
    ],
  },
  resolve: {
    extensions: [".tsx", ".ts", ".js"],
  },
  output: {
    filename: `${packageInfo.name}.js`,
    path: path.resolve(__dirname, "dist"),
    clean: true,
  },
  plugins: [
    new MiniCssExtractPlugin({ filename: `${packageInfo.name}.css` }),
    new CopyPlugin({
      patterns: [
        {
          from: "./src/lib/weather-icons/icons/*.svg",
          to: "weather-icons/icons/[name][ext]",
        },
        {
          from: "./node_modules/bootstrap-icons/icons/*.svg",
          to: "bootstrap-icons/icons/[name][ext]",
        },
        {
          from: "./node_modules/flag-icons/flags/1x1/*.svg",
          to: "flag-icons/flags/1x1/[name][ext]",
        },
        {
          from: "./node_modules/flag-icons/flags/4x3/*.svg",
          to: "flag-icons/flags/4x3/[name][ext]",
        },
      ],
    }),
  ],
  performance: {
    hints: false,
    maxEntrypointSize: 512000,
    maxAssetSize: 512000,
  },
  cache: {
    type: "filesystem",
  },
};

export default config;
