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

const repoRoot = path.resolve(__dirname, '..');

function resolveBackendTarget(env: Record<string, string>) {
  const explicitTarget = env.VITE_API_TARGET;
  if (explicitTarget?.startsWith('http')) {
    return explicitTarget.replace(/\/$/, '');
  }

  const apiBaseUrl = env.VITE_API_BASE_URL;
  if (apiBaseUrl?.startsWith('http')) {
    return apiBaseUrl.replace(/\/api\/?$/, '').replace(/\/$/, '');
  }

  return `http://localhost:${env.SERVER_PORT || env.BACKEND_PORT || '8081'}`;
}

function resolvePort(value: string | undefined, fallback: number) {
  const parsed = Number(value);
  return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
}

export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, repoRoot, '');

  return {
    envDir: repoRoot,
    plugins: [vue()],
    server: {
      port: resolvePort(env.ADMIN_FRONTEND_PORT, 5174),
      proxy: {
        '/admin-api': {
          target: resolveBackendTarget(env),
          changeOrigin: true,
        },
      },
    },
  };
});
