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";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { storybookTest } from "@storybook/addon-vitest/vitest-plugin";
import { playwright } from "@vitest/browser-playwright";
const dirname =
	typeof __dirname !== "undefined" ? __dirname : path.dirname(fileURLToPath(import.meta.url));

// More info at: https://storybook.js.org/docs/next/writing-tests/integrations/vitest-addon
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,
		allowedHosts: [".ts.net"]
	},
	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}"]
				}
			},
			{
				extends: true,
				plugins: [
					// The plugin will run tests for the stories defined in your Storybook config
					// See options at: https://storybook.js.org/docs/next/writing-tests/integrations/vitest-addon#storybooktest
					storybookTest({
						configDir: path.join(dirname, ".storybook")
					})
				],
				test: {
					name: "storybook",
					browser: {
						enabled: true,
						headless: true,
						provider: playwright({}),
						instances: [
							{
								browser: "chromium"
							}
						]
					}
				}
			}
		]
	}
});
