import { defineConfig } from 'vitest/config'
import type { Plugin } from 'vite'
import { fileURLToPath } from 'node:url'
import { readdirSync } from 'node:fs'
import tailwindcss from '@tailwindcss/vite'
import { visualizer } from 'rollup-plugin-visualizer'

// MPA: raccoglie automaticamente ogni *.html nella root di frontend/ come entry di build.
// { 'index': '/app/index.html', 'scheda': '/app/scheda.html', ... }
const frontendRoot = fileURLToPath(new URL('.', import.meta.url))
const htmlEntries = Object.fromEntries(
  readdirSync(frontendRoot)
    .filter((file) => file.endsWith('.html'))
    .map((file) => [file.slice(0, -'.html'.length), fileURLToPath(new URL(file, import.meta.url))])
)

function mpaRewritePlugin(): Plugin {
  return {
    name: 'mpa-rewrite',
    configureServer(server: any) {
      server.middlewares.use((req: any, _res: any, next: any) => {
        if (
            req.url &&
            !req.url.includes('.') &&
            !req.url.startsWith('/@') &&
            !req.url.startsWith('/api') &&
            !req.url.startsWith('/sanctum') &&
            !req.url.startsWith('/storage') &&
            !req.url.startsWith('/documentation') &&
            !req.url.startsWith('/api-docs') &&
            req.url !== '/'
        ) {
          // Mappa il primo segmento del path sul relativo .html.
          // Es: /scheda/uno-slug -> /scheda.html (lo slug resta leggibile da location.pathname)
          const firstSegment = req.url.split('?')[0].split('/')[1]
          req.url = `/${firstSegment}.html`
        }
        next()
      })
    }
  }
}

export default defineConfig({
  plugins: [
    tailwindcss(),
    visualizer(),
    mpaRewritePlugin()
  ],
  resolve: {
    // Alias lato Vite/bundler: tsconfig `paths` vale solo per il type-check, Vite
    // ha bisogno del proprio alias per risolvere `@/...` a runtime e in build.
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url)),
    },
  },
  build: {
    rollupOptions: {
      // MPA: auto-detect delle pagine. Ogni *.html nella root di frontend/ è un entry
      // (nome = file senza estensione). Aggiungere una pagina = creare il suo .html,
      // nessuna modifica qui. Vedi htmlEntries sotto.
      input: htmlEntries,
    }
  },
  server: {
    host: '0.0.0.0',
    allowedHosts: ['dyncoll-dev.local'],
    port: 5173,
    proxy: {
      '/api-docs': {
        target: 'http://backend:8000',
        changeOrigin: true,
        secure: false,
        rewrite: (path: string) => path.replace(/^\/api-docs/, '/docs')
      },
      '/api': {
        target: 'http://backend:8000',
        changeOrigin: true,
        secure: false // accetta certificati self-signed
      },
      '/sanctum': {
        target: 'http://backend:8000',
        changeOrigin: true,
        secure: false,
      },
      '/storage': {
        target: 'http://backend:8000',
        changeOrigin: true,
        secure: false // accetta certificati self-signed
      },
      // Documentazione utente (MkDocs) — servizio docker `docs`
      '/documentation': {
        target: 'http://docs:8000',
        changeOrigin: true,
        secure: false,
        rewrite: (path: string) => path.replace(/^\/documentation/, '') || '/'
      }
    }
  },
  test: {
    coverage: {
      provider: 'v8',
      reporter: ['text', 'html', 'lcov'],
    },
  }
})
