import type { Config } from 'jest';

const config: Config = {
	// Use ts-jest for TypeScript support
	preset: 'ts-jest',

	// Test environment
	testEnvironment: 'node',

	// Root directories for tests
	roots: ['<rootDir>/tests'],

	// Test file patterns
	testMatch: ['**/__tests__/**/*.+(ts|tsx|js)', '**/?(*.)+(spec|test).+(ts|tsx|js)'],

	// TypeScript transformation
	transform: {
		'^.+\\.(ts|tsx)$': 'ts-jest',
	},

	// Module path aliases matching tsconfig.json
	moduleNameMapper: {
		'^#config/(.*)$': '<rootDir>/src/config/$1',
		'^#config$': '<rootDir>/src/config',
		'^#contracts/(.*)$': '<rootDir>/src/contracts/$1',
		'^#controllers/(.*)$': '<rootDir>/src/controllers/$1',
		'^#controllers$': '<rootDir>/src/models/init-models',
		'^#dto/(.*)$': '<rootDir>/src/dto/$1',
		'^#providers/(.*)$': '<rootDir>/src/providers/$1',
		'^#services/(.*)$': '<rootDir>/src/services/$1',
		'^#middlewares/(.*)$': '<rootDir>/src/middlewares/$1',
		'^#models/(.*)$': '<rootDir>/src/models/$1',
		'^#models$': '<rootDir>/src/models/init-models',
		'^#templates/(.*)$': '<rootDir>/src/templates/$1',
		'^#constants/(.*)$': '<rootDir>/src/constants/$1',
		'^#interfaces/(.*)$': '<rootDir>/src/interfaces/$1',
		'^#strategies/(.*)$': '<rootDir>/src/strategies/$1',
		'^#presenters/(.*)$': '<rootDir>/src/presenters/$1',
		'^#utils/(.*)$': '<rootDir>/src/utils/$1',
		'^#/(.*)$': '<rootDir>/src/$1',
		'^@tests/(.*)$': '<rootDir>/tests/$1',
		'^@factories/(.*)$': '<rootDir>/tests/factories/$1',
		'^@helpers/(.*)$': '<rootDir>/tests/helpers/$1',
		'^@mocks/(.*)$': '<rootDir>/tests/mocks/$1',
		'^@fixtures/(.*)$': '<rootDir>/tests/fixtures/$1',
	},

	// Setup files
	setupFilesAfterEnv: ['<rootDir>/tests/setup.ts'],

	// Coverage configuration
	collectCoverageFrom: [
		'src/**/*.ts',
		'!src/**/*.d.ts',
		'!src/**/index.ts',
		'!src/**/route.ts',
		'!src/**/root.ts',
		'!src/**/*.spec.ts',
		'!src/**/*.test.ts',
	],

	coverageDirectory: '<rootDir>/coverage',
	coverageReporters: ['text', 'text-summary', 'lcov', 'html'],

	// Coverage thresholds
	coverageThreshold: {
		global: {
			branches: 80,
			functions: 80,
			lines: 80,
			statements: 80,
		},
		'./src/services/': {
			branches: 85,
			functions: 85,
			lines: 85,
			statements: 85,
		},
	},

	// Test timeout
	testTimeout: 10000,

	// Verbose output
	verbose: true,

	// Clear mocks between tests
	clearMocks: true,
	restoreMocks: true,

	// Fail on console errors/warnings in tests
	errorOnDeprecated: true,

	// Detect open handles (async operations not cleaned up)
	detectOpenHandles: true,

	// Force exit after all tests complete
	forceExit: true,

	// ts-jest specific options
	globals: {
		'ts-jest': {
			tsconfig: 'tsconfig.json',
			isolatedModules: true,
			diagnostics: {
				ignoreCodes: [151002],
			},
		},
	},
};

export default config;
