import { defineConfig, loadEnv, type Plugin } from 'vite' // Zmieniono na 'type Plugin'
import react from '@vitejs/plugin-react'
import tailwindcss from '@tailwindcss/vite'
import path from 'path'

// Plugin obsługujący logikę przekierowań
const domainRedirectPlugin = (targetUrl: string, useSubdomains: boolean, debug: boolean): Plugin => ({
    name: 'domain-redirect',
    configureServer(server) {
        server.middlewares.use((req, res, next) => {
            const host = req.headers.host; // np. "ssss.localhost:6568"
            if (!host) return next();

            const hostname = host.split(':')[0]; // usuwamy port, zostaje "ssss.localhost"
            const targetHost = new URL(targetUrl).hostname;

            // LOGIKA TESTOWA DLA LOCALHOST:
            // Jeśli host to np. ssss.localhost, a nie czysty localhost:
            const isSubdomainOfLocalhost = hostname.endsWith('.localhost');
            const isPureLocalhost = hostname === 'localhost' || hostname === '127.0.0.1';

            if (debug) {
                console.log(`[Debug] Host: ${hostname}, SubOfLocal: ${isSubdomainOfLocalhost}, Pure: ${isPureLocalhost}`);
            }

            // Przekieruj jeśli:
            // 1. To subdomena localhosta (do testów)
            // 2. LUB to subdomena ktty.is, a subdomeny są wyłączone
            if ((isSubdomainOfLocalhost && hostname !== 'localhost') || (useSubdomains && hostname !== targetHost && !isPureLocalhost)) {
                if (debug) console.log(`[Redirect] Z ${hostname} na ${targetUrl}`);

                res.writeHead(301, { Location: `${targetUrl}${req.url}` });
                return res.end();
            }

            next();
        });
    }
});

export default defineConfig(({ mode }) => {
    const envDirectory = path.resolve(__dirname, '..');
    const env = loadEnv(mode, envDirectory, '');

    // Twoje zmienne z .env
    const publicUrl = env.PUBLIC_URL;
    const useSubdomains = env.USE_SUBDOMAINS === 'true';
    const isDebug = env.DEBUG === 'true';

    return {
        envDir: envDirectory,
        plugins: [
            react(),
            tailwindcss(),
            domainRedirectPlugin(publicUrl, useSubdomains, isDebug)
        ],
        server: {
            port: 6568,
            host: true,
        },
        preview: {
            port: 6568,
            
            allowedHosts: [env.VITE_ALLOWED_HOST , 'localhost'],
        },
    }
})