// SPDX-License-Identifier: GPL-3.0-or-later

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import path from 'path';
import fs from 'fs';

// Check if we're running in Tauri
const isTauri = process.env.TAURI_ENV_PLATFORM !== undefined;

// HTTPS configuration with mkcert certificates
const httpsConfig = () => {
  const certPath = path.resolve(__dirname, 'certs/cert.pem');
  const keyPath = path.resolve(__dirname, 'certs/key.pem');
  
  if (fs.existsSync(certPath) && fs.existsSync(keyPath)) {
    return {
      key: fs.readFileSync(keyPath),
      cert: fs.readFileSync(certPath),
    };
  }
  
  console.warn('⚠️  HTTPS certificates not found. Run: npm run cert:generate');
  return undefined;
};

export default defineConfig({
  plugins: [react()],
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src'),
    },
  },
  server: {
    port: 1212,
    strictPort: true,
    https: httpsConfig(),
    proxy: {
      '/api': {
        target: 'http://127.0.0.1:62774',
        changeOrigin: true,
        secure: false,
      },
    },
  },
  preview: {
    port: 1212,
    strictPort: true,
    https: httpsConfig(),
  },
  // Tauri expects a fixed port
  clearScreen: false,
  // Prevent vite from obscuring Rust errors
  envPrefix: ['VITE_', 'TAURI_ENV_*'],
  build: {
    // Tauri uses Chromium on Windows and WebKit on macOS and Linux
    target: isTauri
      ? process.env.TAURI_ENV_PLATFORM === 'windows'
        ? 'chrome105'
        : 'safari13'
      : 'esnext',
    // Don't minify for debug builds
    minify: !process.env.TAURI_ENV_DEBUG ? 'esbuild' : false,
    // Produce sourcemaps for debug builds
    sourcemap: !!process.env.TAURI_ENV_DEBUG,
  },
});
