import tailwindcss from '@tailwindcss/vite';
import { sveltekit } from '@sveltejs/kit/vite';
import Icons from 'unplugin-icons/vite';
import { defineConfig } from 'vitest/config';
import oauthMetadata from './static/oauth-client-metadata.json';

const devHost = process.env.VITE_DEV_HOST ?? '127.0.0.1';
const devPort = Number(process.env.VITE_DEV_PORT ?? 5173);
const devRedirectUri = `http://127.0.0.1:${devPort}/oauth/callback`;
const devClientId = `http://localhost?redirect_uri=${encodeURIComponent(devRedirectUri)}&scope=${encodeURIComponent(oauthMetadata.scope)}`;

export default defineConfig({
	plugins: [
		{
			name: 'oauth-env',
			config(_config, { command }) {
				process.env.VITE_OAUTH_CLIENT_ID ??=
					command === 'serve' ? devClientId : oauthMetadata.client_id;
				process.env.VITE_OAUTH_REDIRECT_URI ??=
					command === 'serve' ? devRedirectUri : oauthMetadata.redirect_uris[0];
				process.env.VITE_OAUTH_SCOPE ??= oauthMetadata.scope;
			}
		},
		tailwindcss(),
		Icons({ compiler: 'svelte' }),
		sveltekit()
	],
	resolve: {
		alias: {
			'$icon/': '~icons/lucide/'
		}
	},
	server: {
		host: devHost,
		port: devPort,
		strictPort: true
	},
	test: {
		expect: { requireAssertions: true },
		projects: [
			{
				extends: './vite.config.ts',
				test: {
					name: 'server',
					environment: 'node',
					include: ['src/**/*.{test,spec}.{js,ts}'],
					exclude: ['src/**/*.svelte.{test,spec}.{js,ts}']
				}
			}
		]
	}
});
