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

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
}

function figmaAssetResolver() {
  return {
    name: 'figma-asset-resolver',
    resolveId(id) {
      if (id.startsWith('figma:asset/')) {
        const filename = id.replace('figma:asset/', '')
        return path.resolve(__dirname, 'src/assets', filename)
      }
    },
  }
}

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

  return {
    envDir: repoRoot,
    plugins: [
      figmaAssetResolver(),
      // The React and Tailwind plugins are both required for Make, even if
      // Tailwind is not being actively used – do not remove them
      react(),
      tailwindcss(),
    ],
    resolve: {
      alias: {
        // Alias @ to the src directory
        '@': path.resolve(__dirname, './src'),
      },
    },
    server: {
      host: true,
      port: resolvePort(env.FRONTEND_PORT, 5173),
      allowedHosts: true,
      proxy: {
        '/api': {
          target: resolveBackendTarget(env),
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, ''),
        },
      },
    },

    // File types to support raw imports. Never add .css, .tsx, or .ts files to this.
    assetsInclude: ['**/*.svg', '**/*.csv'],
  }
})
