import { fileURLToPath, URL } from 'node:url'
import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import fs from 'fs'

export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd(), '')
  const backendHost = env.VITE_BACKEND_HOST ?? '127.0.0.1'

  // Use a trusted mkcert cert when present; otherwise fall back to plain HTTP.
  // Browsers treat localhost as a secure context even over HTTP, so service
  // workers and push notifications work without any cert on localhost.
  //
  // For cross-device LAN testing (e.g. from a phone), run mkcert once per
  // network — the IP in the cert doesn't matter to Vite, just drop the files
  // in frontend/ and they'll be picked up automatically:
  //
  //   mkcert localhost <your-current-lan-ip>
  //   # files are auto-detected; no renaming needed
  //
  // All *.pem files are gitignored so they stay machine-local.
  const httpsConfig = (() => {
    // Prefer explicit key.pem / cert.pem (e.g. custom or renamed certs)
    if (fs.existsSync('./key.pem') && fs.existsSync('./cert.pem'))
      return { key: fs.readFileSync('./key.pem'), cert: fs.readFileSync('./cert.pem') }
    // Auto-detect any mkcert-generated *-key.pem / *.pem pair in this directory.
    // mkcert always names files <host>[-key].pem regardless of which IPs are included.
    const keyFile = fs.readdirSync('.').find((f) => f.endsWith('-key.pem'))
    if (keyFile) {
      const certFile = keyFile.replace('-key.pem', '.pem')
      if (fs.existsSync(certFile))
        return { key: fs.readFileSync(keyFile), cert: fs.readFileSync(certFile) }
    }
    return undefined
  })()

  return {
    plugins: [vue()],
    server: {
      host: '0.0.0.0',
      https: httpsConfig,
      proxy: {
        '/api': {
          target: `http://${backendHost}:5000`,
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, ''),
        },
        '/events': {
          target: `http://${backendHost}:5000`,
          changeOrigin: true,
          secure: false,
        },
      },
    },
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url)),
      },
    },
  }
})
