import { defineConfig } from 'vitest/config';
import { playwright } from '@vitest/browser-playwright';
import tailwindcss from '@tailwindcss/vite';
import { sveltekit } from '@sveltejs/kit/vite';
import { VitePWA } from 'vite-plugin-pwa';

const backendTarget = process.env.BACKEND_URL ?? 'http://localhost:3000';
const enableProxy = process.env.USE_VITE_PROXY === 'true';

const proxiedPaths = [
	'/api',
	'/devices',
	'/device-links',
	'/streams',
	'/events',
	'/recordings',
	'/videos',
	'/push-notifications',
	'/socket.io'
] as const;

const proxy = Object.fromEntries(
	proxiedPaths.map((path) => [
		path,
		{
			target: backendTarget,
			changeOrigin: true,
			ws: path === '/socket.io'
		}
	])
);

export default defineConfig({
	plugins: [
		tailwindcss(),
		sveltekit(),
		VitePWA({
			injectRegister: false,
			registerType: 'autoUpdate',
			includeAssets: ['icons/apple-touch-icon.png', 'icons/pwa-192x192.png', 'icons/pwa-512x512.png'],
			manifest: {
				name: 'PhoneCam Web Dashboard',
				short_name: 'PhoneCam',
				description: 'Monitor camera devices, motion events, and recordings from an installable web dashboard.',
				theme_color: '#0a0a0c',
				background_color: '#0a0a0c',
				display: 'standalone',
				start_url: '/',
				scope: '/',
				orientation: 'portrait-primary',
				icons: [
					{
						src: 'icons/pwa-192x192.png',
						sizes: '192x192',
						type: 'image/png',
						purpose: 'any'
					},
					{
						src: 'icons/pwa-512x512.png',
						sizes: '512x512',
						type: 'image/png',
						purpose: 'any'
					},
					{
						src: 'icons/maskable-512x512.png',
						sizes: '512x512',
						type: 'image/png',
						purpose: 'maskable'
					}
				]
			},
			workbox: {
				globPatterns: ['**/*.{js,css,html,ico,png,svg,webmanifest}'],
				navigateFallbackDenylist: [/^\/api\//, /^\/devices/, /^\/device-links/, /^\/streams/, /^\/events/, /^\/recordings/, /^\/videos/, /^\/push-notifications/, /^\/socket\.io\//]
			},
			devOptions: {
				enabled: false
			}
		})
	],
	server: {
		proxy: enableProxy ? proxy : undefined
	},
	test: {
		expect: { requireAssertions: true },
		projects: [
			{
				extends: './vite.config.ts',
				test: {
					name: 'client',
					browser: {
						enabled: true,
						provider: playwright(),
						instances: [{ browser: 'chromium', headless: true }]
					},
					include: ['src/**/*.svelte.{test,spec}.{js,ts}'],
					exclude: ['src/lib/server/**']
				}
			},

			{
				extends: './vite.config.ts',
				test: {
					name: 'server',
					environment: 'node',
					include: ['src/**/*.{test,spec}.{js,ts}'],
					exclude: ['src/**/*.svelte.{test,spec}.{js,ts}']
				}
			}
		]
	}
});
