import { readdirSync, existsSync } from 'node:fs'
import { resolve } from 'node:path'

// Auto-detect module layers: every directory under frontend/modules/ becomes a Nuxt layer.
const modulesDir = resolve(__dirname, 'modules')
const moduleDirs = existsSync(modulesDir)
    ? readdirSync(modulesDir, { withFileTypes: true })
        .filter(d => d.isDirectory())
        .map(d => d.name)
    : []
const moduleLayers = moduleDirs.map(name => `./modules/${name}`)

// Auto-detect composables dirs pour chaque layer module. Necessaire car le
// `imports.dirs` explicite ci-dessous override le comportement par defaut
// de Nuxt (qui scannerait composables/ de chaque layer automatiquement).
// Sans ca, useCurrentSite / autres composables des modules ne seraient pas
// resolus a l'execution — cf. ticket 3 bug detecte apres review.
const moduleComposableDirs = moduleDirs
    .map(name => `./modules/${name}/composables`)
    .filter(path => existsSync(resolve(__dirname, path)))

export default defineNuxtConfig({
    compatibilityDate: '2025-07-15',
    devtools: {enabled: false},
    ssr: false,
    srcDir: '.',
    css: ['~/assets/css/main.css'],
    app: {
        baseURL: process.env.NODE_ENV === 'production'
            ? (process.env.NUXT_PUBLIC_APP_BASE || '/')
            : '/'
    },
    extends: [
        '@malio/layer-ui',
        ...moduleLayers,
    ],
    modules: [
        '@nuxtjs/tailwindcss',
        '@pinia/nuxt',
        'nuxt-toast',
        '@nuxtjs/i18n',
        '@nuxt/icon',
    ],
    runtimeConfig: {
        public: {
            apiBase: process.env.NUXT_PUBLIC_API_BASE
        }
    },
    devServer: {
        port: 3004,
    },
    dir: {
        layouts: 'app/layouts',
        middleware: 'app/middleware',
    },
    components: [
        {path: '~/shared/components', pathPrefix: false},
    ],
    imports: {
        dirs: [
            'shared/composables',
            'shared/utils',
            'shared/stores',
            ...moduleComposableDirs,
        ],
    },
    vite: {
        server: {
            allowedHosts: true,
            proxy: {
                '/api': {
                    target: 'http://nginx',
                    changeOrigin: true,
                },
            },
        },
    },
    toast: {
        settings: {
            timeout: 2000,
            closeOnClick: true,
            progressBar: false
        }
    },
    i18n: {
        strategy: 'no_prefix',
        defaultLocale: 'fr',
        langDir: 'locales',
        locales: [
            {code: 'fr', file: 'fr.json', name: 'Français'}
        ],
    },
    typescript: {
        strict: true
    },
})
