// @ts-check
import { defineConfig } from 'astro/config';
import node from '@astrojs/node';
import tailwindcss from '@tailwindcss/vite';
import vue from '@astrojs/vue';
import ui from '@nuxt/ui/vite';
import { loadEnv } from 'vite';

function get_baseUrl() {
    const viteMode = process.env.NODE_ENV === 'production' ? 'production' : 'development';
    const env = loadEnv(viteMode, process.cwd(), '');
    const drupalTarget = (env.PUBLIC_DRUPAL_BASE_URL || '').replace(/\/+$/, '');
    return drupalTarget;
}

// https://astro.build/config
export default defineConfig({
    devToolbar: { enabled: false },
    adapter: node({
        mode: 'standalone',
    }),
    integrations: [
        vue({
        jsx: true,
        appEntrypoint: './src/vue-app.ts',
        }),
    ],
    vite: {
        build: { sourcemap: true },
        plugins: [tailwindcss(), ui({ router: false })],

        // Same-origin proxy in dev so browser JSON:API calls avoid CORS.
        // When the dev server receives a request starting with `/__drupal`, it will:
        //   - Forward (proxy) that request to `drupalTarget`, which is the Drupal backend URL from .env
        //   - Remove the `/__drupal` prefix before sending it to Drupal (so `/__drupal/jsonapi/node/article` becomes `/jsonapi/node/article`)
        //   - Set `changeOrigin: true` so the Drupal server sees the correct Host header
        //   - Set `secure: false` to ignore SSL certificate issues (handy for local dev)
        // If `drupalTarget` is not configured, no proxy is set up.
        server: {
        proxy: get_baseUrl()
            ? {
                '/__drupal': {
                target: get_baseUrl(),
                changeOrigin: true,
                secure: false,
                rewrite: (path) => path.replace(/^\/__drupal/, '') || '/',
                },
            }
            : {},
        },
    },
});