// This file has been automatically migrated to valid ESM format by Storybook.
import { fileURLToPath } from 'node:url';
import { createRequire } from 'node:module';
import path, { dirname } from 'path';

import { StorybookConfig } from '@storybook/react-webpack5';

import { Configuration } from 'webpack';
import postcss from 'postcss';

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

const config: StorybookConfig = {
  stories: ['../app/**/*.stories.@(ts|tsx)'],
  addons: [
    '@storybook/addon-links',
    '@storybook/addon-webpack5-compiler-swc',
    '@chromatic-com/storybook',
    {
      name: '@storybook/addon-styling-webpack',

      options: {
        rules: [
          {
            test: /\.css$/,
            sideEffects: true,
            use: [
              require.resolve('style-loader'),
              {
                loader: require.resolve('css-loader'),
                options: {
                  importLoaders: 1,
                  modules: {
                    localIdentName: '[path][name]__[local]',
                    auto: true,
                    exportLocalsConvention: 'camelCaseOnly',
                  },
                },
              },
              {
                loader: require.resolve('postcss-loader'),
                options: {
                  implementation: postcss,
                },
              },
            ],
          },
        ],
      },
    },
    '@storybook/addon-docs',
  ],
  webpackFinal: (config) => {
    const rules = config?.module?.rules || [];

    const imageRule = rules.find((rule) => {
      const test = (rule as { test: RegExp }).test;

      if (!test) {
        return false;
      }

      return test.test('.svg');
    }) as { [key: string]: any };

    imageRule.exclude = /\.svg$/;

    rules.unshift({
      test: /\.svg$/i,
      type: 'asset',
      resourceQuery: {
        not: [/c/],
      }, // exclude react component if *.svg?url
    });

    rules.unshift({
      test: /\.svg$/i,
      issuer: /\.(js|ts)(x)?$/,
      resourceQuery: /c/,
      // *.svg?c
      use: [
        {
          loader: '@svgr/webpack',
          options: {
            icon: true,
          },
        },
      ],
    });
    return {
      ...config,
      resolve: {
        ...config.resolve,
        tsconfig: path.resolve(__dirname, '..', 'tsconfig.json'),
      },
      module: {
        ...config.module,
        rules,
      },
    } satisfies Configuration;
  },
  staticDirs: ['./public'],
  typescript: {
    reactDocgen: 'react-docgen',
  },
  framework: {
    name: '@storybook/react-webpack5',
    options: {},
  },
  docs: {},
};

export default config;
