import {fileURLToPath, URL} from 'node:url'
import {execSync} from 'node:child_process'
import {existsSync} from 'node:fs'

import {defineConfig} from 'vite'
import vue from '@vitejs/plugin-vue'

function gitCommit() {
    // deploy/dev/docker-compose.yml bind-mounts the repo's real .git dir at
    // /git (separate from /app, which only has the frontend/ subtree) -
    // point git at it explicitly there. Bare-metal dev has no such mount,
    // but this file's cwd sits inside the real checkout so plain rev-parse
    // finds it by walking up. In prod, the build context is frontend/ alone
    // with no .git anywhere, so both fail and we fall back to the
    // GIT_COMMIT build-arg/env var (see deploy/prod/Dockerfile.frontend and
    // playbook.yml).
    const gitDirFlag = existsSync('/git') ? '--git-dir=/git ' : ''
    try {
        return execSync(`git ${gitDirFlag}rev-parse --short HEAD`).toString().trim()
    } catch {
        return process.env.GIT_COMMIT || 'unknown'
    }
}

export default defineConfig({
    plugins: [vue()],
    define: {
        __GIT_COMMIT__: JSON.stringify(gitCommit())
    },
    resolve: {
        alias: {
            '@': fileURLToPath(new URL('./src', import.meta.url))
        }
    },
    server: {
        host: true,
        cors: true,
        headers: {
            //allow all origins
            'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
            'Access-Control-Allow-Headers': 'Origin, Content-Type, X-Auth-Token, Authorization, Accept, charset, boundary, Content-Length',
            'Access-Control-Allow-Credentials': 'true',
            'Access-Control-Max-Age': '86400',
            //'Upgrade-Insecure-Requests': '1',
            'Content-Security-Policy': 'default-src \'self\';'
                + ' script-src \'self\' \'wasm-unsafe-eval\' \'unsafe-eval\' \'unsafe-inline\';'
                + ' style-src \'self\' \'unsafe-inline\';'
                + ' img-src \'self\' * data: blob:;'
                + ' connect-src * data:',
        },
    },
    test: {
        include: ['src/tests/**/*.js'],
        globals: true,
        environment: "jsdom"
    }
})
