import type { Config } from 'jest';
import nextJest from 'next/jest.js';

// const nextJest = require('next/jest');

const createJestConfig = nextJest({
  // Provide the path to your Next.js app to load next.config.* and .env files in your test environment
  dir: './',
});

// Add any custom config to be passed to Jest
const customJestConfig: Config = {
  coverageProvider: 'v8',
  setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
  moduleNameMapper: {
    // Handle the `@/*` alias — it maps to `src/*` (see tsconfig.json), so jest.mock('@/…')
    // and imports resolve to the same files the app uses.
    '^@/(.*)$': '<rootDir>/src/$1',
  },
  // testEnvironment: 'jest-environment-jsdom',
  testEnvironment: 'jsdom',
  // transform: {
  //   '.+\\.(css|styl|less|sass|scss)$': 'jest-css-modules-transform',
  // },
};

// next-intl (and its use-intl dependency) ship ESM-only builds. next/jest's own
// `transformIgnorePatterns` already broadly matches all of node_modules (its negative-lookahead
// allowlist only carves out a couple of Next.js-internal packages), and Jest's array semantics
// are OR-based — a file is ignored if ANY pattern matches, so appending a more permissive pattern
// can never "un-ignore" a package an earlier pattern already caught. The array has to be replaced
// outright (post-processing the async config next/jest returns), not merged, to let a real
// (unmocked) `import ... from 'next-intl'` be transformed instead of failing to parse. Without
// this, any shared component that imports next-intl (even just for a sensible default) would
// force every test file that transitively imports it via the `@/components` barrel to
// `jest.mock('next-intl', …)`, even when that test never touches translations itself.
const withTransformableIntl = async () => {
  const config = await createJestConfig(customJestConfig)();
  config.transformIgnorePatterns = [
    '/node_modules/(?!(geist|next/dist/client|next/dist/shared/lib|next/src/client|next/src/shared/lib|next-intl|use-intl|@formatjs|intl-messageformat)/)',
    '^.+\\.module\\.(css|sass|scss)$',
  ];
  return config;
};

module.exports = withTransformableIntl;
