import { fileURLToPath, URL } from 'node:url'

import { defineConfig } from 'vite'
import { resolve } from 'node:path'
import vue from '@vitejs/plugin-vue'

// https://vite.dev/config/
export default defineConfig(({ command, mode }) => ({
  plugins: [
    vue(),
  ],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    },
  },
  // Use absolute paths at dev, deploy under /auth/
  base: command === 'build' ? '/auth/' : '/',
  server: {
    port: 4403,
    proxy: {
      '/auth/': {
        target: 'http://localhost:4402',
        ws: true,
        changeOrigin: false,
        // We proxy API + WS under /auth/, but want Vite to serve the SPA entrypoints
        // and static assets so that HMR works. Bypass tells http-proxy to skip
        // proxying when we return a (possibly rewritten) local path.
        bypass(req) {
          const rawUrl = req.url || ''
          // Strip query/hash to match path-only for SPA entrypoints with query params (e.g. ?reset=token)
          const url = rawUrl.split('?')[0].split('#')[0]
          // Bypass only root SPA entrypoints + static assets so Vite serves them for HMR.
          // Admin API endpoints (e.g., /auth/admin/orgs) must still hit backend.
          if (url === '/auth/' || url === '/auth') return '/'
          if (url === '/auth/admin' || url === '/auth/admin/') return '/admin/'
          if (url.startsWith('/auth/assets/')) return url.replace(/^\/auth/, '')
          if (/^\/auth\/([a-z]+\.){4}[a-z]+\/?$/.test(url)) return '/reset/index.html'
          if (/^\/([a-z]+\.){4}[a-z]+\/?$/.test(url)) return '/reset/index.html'
          if (url === '/auth/restricted' || url === '/auth/restricted/') return '/restricted/index.html'
          if (url === '/restricted' || url === '/restricted/') return '/restricted/index.html'
          // Everything else (including /auth/admin/* APIs) should proxy.
        }
      }
    }
  },
  build: {
    outDir: '../passkey/frontend-build',
    emptyOutDir: true,
    assetsDir: 'assets',
    rollupOptions: {
      input: {
        index: resolve(__dirname, 'index.html'),
        admin: resolve(__dirname, 'admin/index.html'),
        reset: resolve(__dirname, 'reset/index.html'),
        restricted: resolve(__dirname, 'restricted/index.html')
      },
      output: {}
    }
  }
}))
