import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import { wayfinder } from '@laravel/vite-plugin-wayfinder';
import react from '@vitejs/plugin-react';
import tailwindcss from '@tailwindcss/vite';
import path from 'path';

// ---------------------------------------------------------------------------
// Dynamic server config — controlled entirely via .env
// ---------------------------------------------------------------------------
// Without Docker (localhost):
//   VITE_BACKEND_URL=http://localhost:8000
//   VITE_HMR_HOST=localhost
//
// With Docker (service name):
//   VITE_BACKEND_URL=http://taskco-app:8000
//   VITE_HMR_HOST=admin.app.taskco.local
//
// Custom domain / remote server:
//   VITE_BACKEND_URL=http://api.yourdomain.com
//   VITE_HMR_HOST=admin.yourdomain.com
// ---------------------------------------------------------------------------

const BUILD_DIR   = 'build'; // This is the directory where Vite will output built assets. It should match the "buildDirectory" option in laravel-vite-plugin and the "public_path" in config/filesystems.php.

const backendUrl  = process.env.VITE_BACKEND_URL   || 'http://localhost:8000';
const hmrHost     = process.env.VITE_HMR_HOST      || 'localhost';
const hmrClientPort = process.env.VITE_HMR_CLIENT_PORT ? parseInt(process.env.VITE_HMR_CLIENT_PORT) : undefined;
const usePolling  = process.env.CHOKIDAR_USEPOLLING === 'true';

export default defineConfig({
    plugins: [
        laravel({
            input: ['resources/js/app.tsx'],
            refresh: true,
            buildDirectory: BUILD_DIR
        }),
        /*wayfinder({
            command: "docker exec taskco-app php artisan wayfinder:generate"
        }),*/
        react(),
        tailwindcss(),
    ],

    server: {
        host: '0.0.0.0',
        port: parseInt(process.env.VITE_DEV_SERVER_PORT || '5176'),
        strictPort: true,
        cors: true,
        https: undefined,
        hmr: {
            host: hmrHost,
            // clientPort is only set when routing HMR through a reverse proxy
            // (e.g. nginx on a different port). Without it, laravel-vite-plugin
            // writes the actual server port into public/hot — which is what we want.
            ...(hmrClientPort !== undefined ? { clientPort: hmrClientPort } : {}),
        },

        watch: {
            usePolling: usePolling,
            interval: 1000,
            ignored: ['**/node_modules/**', '**/vendor/**'],
        },

        proxy: {
            '/api': {
                target: backendUrl,
                changeOrigin: true,
                secure: false,
            },
            '/ws': {
                target: backendUrl.replace(/^http/, 'ws'),
                ws: true,
            },
        },
    },

    build: {
        outDir: `public/${BUILD_DIR}`,
        emptyOutDir: true,
        manifest: true,
        minify: 'esbuild',
        sourcemap: false,
        cssCodeSplit: true,
        chunkSizeWarningLimit: 1500,
        rollupOptions: {
            input: 'resources/js/app.tsx',
            output: {
                entryFileNames: 'assets/[name].[hash].js',
                chunkFileNames: 'assets/[name].[hash].js',
                assetFileNames: 'assets/[name].[hash].[ext]',
            },
        },
    },
    resolve: {
        alias: {
            '@': path.resolve(__dirname, 'resources/js'),
            '@admin': path.resolve(__dirname, 'AdminApp/resources/assets'),
        },
    },

    esbuild: {
        jsx: 'automatic',
        drop: process.env.NODE_ENV === 'production' ? ['console', 'debugger'] : [],
    },

    optimizeDeps: {
        include: [
            'react',
            'react-dom',
            'react/jsx-runtime',
            '@inertiajs/react',
            'react-hook-form',
            'zod',
        ],
        exclude: [
            '@react-types/shared',
            '@radix-ui/react-*',
        ],
    },
});
