import react from '@vitejs/plugin-react';
import fs from 'fs';
import { createRequire } from 'module';
import path from 'path';
import { fileURLToPath, pathToFileURL } from 'url';
import { defineConfig } from 'vite';
import svgr from 'vite-plugin-svgr';
import topLevelAwait from 'vite-plugin-top-level-await';

const require = createRequire(import.meta.url);

let paths = {};

function appendForwardSlash(path: string) {
	return path.endsWith('/') ? path : path + '/';
}

const root = pathToFileURL(path.resolve(process.cwd(), '../../..'));
// Append forward slash to compute relative paths
root.href = appendForwardSlash(root.href);

console.log({ __dirname, root });

let hasTSConfig = false;

try {
	if (fs.existsSync(fileURLToPath(new URL('./tsconfig.json', root)))) {
		console.log('tsconfig.json found');
		hasTSConfig = true;
	}
} catch {
	console.error('tsconfig.json not found');
}

const tsconfig = hasTSConfig
	? JSON.parse(fs.readFileSync(fileURLToPath(new URL('./tsconfig.json', root))))
	: false;

// translate tsconfig paths to vite paths
if (tsconfig && tsconfig.compilerOptions.paths) {
	Object.keys(tsconfig.compilerOptions.paths).forEach((key) => {
		paths[key.split('/*')[0]] = path.resolve(
			fileURLToPath(root),
			tsconfig.compilerOptions.paths[key][0].split('/*')[0]
		);
	});
}

console.log(fileURLToPath(new URL('./', root)));

// https://vitejs.dev/config/
export default defineConfig({
	plugins: [
		svgr(),
		react(),
		topLevelAwait({
			promiseExportName: '__tla',
			promiseImportName: (i) => `__tla_${i}`,
		}),
	],
	envPrefix: 'NITRO_',
	envDir: fileURLToPath(new URL('./', root)),
	optimizeDeps: {
		include: [
			'core-js',
			'simplebar',
			'simplebar-react',
			'can-use-dom',
			'lodash.debounce',
			'lodash.throttle',
			'lodash.memoize',
			'prop-types',
			'react',
			'react/jsx-runtime',
			'react/jsx-dev-runtime',
			'react-dom',
			'classnames',
			'path',
			'react-dom/client',
		],
	},
	server: {
		hmr: false,
		fs: {
			allow: [fileURLToPath(root)],
		},
	},
	build: {
		target: 'esnext',
		minify: false,
	},
	resolve: {
		alias: {
			...paths,
			// '@parent': fileURLToPath(root),
			fs: require.resolve('rollup-plugin-node-builtins'),
			url: require.resolve('rollup-plugin-node-builtins'),
		},
	},
	css: {
		modules: {
			generateScopedName: '[name]__[local]',
		},
	},
});
