import moduleAlias from 'module-alias';
import { FOLDERS } from './constants/index';
import { root } from './root';
import 'dotenv/config';

// ── Dev secrets: set BEFORE any module is loaded ────────────────────────────────
if (process.env.NODE_ENV === 'development' || process.env.NODE_ENV === undefined) {
	if (!process.env.JWT_SECRET || process.env.JWT_SECRET.length < 32) {
		process.env.JWT_SECRET = 'dev_jwt_secret_key_minimum_32_chars!!';
	}
	if (!process.env.JWT_REFRESH_SECRET || process.env.JWT_REFRESH_SECRET.length < 32) {
		process.env.JWT_REFRESH_SECRET = 'dev_refresh_secret_key_minimum_32_chars!!';
	}
	if (!process.env.TOKEN_ENCRYPTION_KEY || process.env.TOKEN_ENCRYPTION_KEY.length < 32) {
		process.env.TOKEN_ENCRYPTION_KEY = 'dev_encryption_key_exactly_32_chars!';
	}
	if (!process.env.OIDC_COOKIE_KEYS) {
		process.env.OIDC_COOKIE_KEYS = 'dev_cookie_key_at_least_32_chars!!';
	}
	if (!process.env.DEFAULT_PASSWORD) {
		process.env.DEFAULT_PASSWORD = 'Vietpro@123';
	}
}

moduleAlias.addAliases({
	'#': __dirname,
	...FOLDERS.reduce(
		(folderAlias, folder) => Object.assign(folderAlias, { [`#${folder}`]: `${__dirname}/${folder}` }),
		{},
	),
});
moduleAlias();

// Set global base directory
(global as any).__baseDir = root;

// Validate required environment variables before starting the server
import { validateEnv } from './utils/envValidator';
validateEnv();

const { startServer } = require('./server');
import type { Environment } from './interfaces/IEnv';

// eslint-disable-next-line no-restricted-syntax
startServer(<Environment>(process.env.NODE_ENV?.toLowerCase() ?? 'development'));
