import { sveltekit } from '@sveltejs/kit/vite';
import { defineConfig, loadEnv } from 'vite';

export default defineConfig(({ mode }) => {
    // Pull in .env so VITE_PORT / BACKEND_URL pin the dev URL across runs.
    // Empty prefix loads every key, not just VITE_*.
    const env = { ...process.env, ...loadEnv(mode, process.cwd(), '') };
    return {
        plugins: [sveltekit()],
        server: {
            port: Number(env.VITE_PORT ?? 5173),
            strictPort: env.VITE_PORT != null,
            proxy: {
                '/api': {
                    target: env.BACKEND_URL ?? 'http://localhost:8080',
                    changeOrigin: true
                }
            }
        },
        test: {
            environment: 'jsdom',
            include: ['src/**/*.test.ts'],
            globals: false
        },
        resolve: {
            // Use Svelte's browser entry under vitest so component tests can
            // mount with @testing-library/svelte. The default (server entry)
            // throws lifecycle_function_unavailable on mount().
            conditions: mode === 'test' ? ['browser'] : []
        }
    };
});
