import { readFileSync } from 'node:fs';
import { fileURLToPath, URL } from 'node:url';

import { defineConfig } from 'vite';
import solid from 'vite-plugin-solid';

const SERVER_HOST = '127.0.0.1';
const SERVER_PORT = 12520;
const metadataPath = fileURLToPath(new URL('./public/oauth-client-metadata.json', import.meta.url));
const metadata = JSON.parse(readFileSync(metadataPath, 'utf8')) as {
	client_id: string;
	redirect_uris: string[];
	scope: string;
};

export default defineConfig(({ command }) => {
	if (command === 'build') {
		process.env.VITE_OAUTH_CLIENT_ID = metadata.client_id;
		process.env.VITE_OAUTH_REDIRECT_URI = metadata.redirect_uris[0];
	} else {
		const redirectPathname = new URL(metadata.redirect_uris[0]).pathname;
		const redirectUri = `http://${SERVER_HOST}:${SERVER_PORT}${redirectPathname}`;

		process.env.VITE_OAUTH_CLIENT_ID =
			`http://localhost?redirect_uri=${encodeURIComponent(redirectUri)}` +
			`&scope=${encodeURIComponent(metadata.scope)}`;
		process.env.VITE_OAUTH_REDIRECT_URI = redirectUri;
	}

	process.env.VITE_OAUTH_SCOPE = metadata.scope;

	return {
		server: {
			host: SERVER_HOST,
			port: SERVER_PORT,
		},
		preview: {
			host: SERVER_HOST,
			port: SERVER_PORT,
		},
		plugins: [solid()],
		build: {
			sourcemap: true,
		},
	};
});
