// vitest.config.integration.ts
import { defineConfig, mergeConfig } from 'vitest/config';
import type { UserConfig } from 'vite';
import viteConfig from './vite.config';
import * as fs from 'fs';
import * as path from 'path';

// Ensure NODE_ENV is set to 'test' for all Vitest runs.
process.env.NODE_ENV = 'test';

// 1. Separate the 'test' config (which has Unit Test settings)
//    from the rest of the general Vite config (plugins, aliases, etc.)
// DEBUG: Use console.error to ensure logs appear in CI/CD output
console.error(`[DEBUG] Loading vitest.config.integration.ts at ${new Date().toISOString()}...`);
console.error(`[DEBUG] CWD: ${process.cwd()}`);

// Check if the integration test directory exists and list its contents
const integrationTestDir = path.resolve(process.cwd(), 'src/tests/integration');
try {
  const files = fs.readdirSync(integrationTestDir);
  console.error(
    `[DEBUG] Integration test directory (${integrationTestDir}) contains ${files.length} files:`,
  );
  files.forEach((f) => console.error(`[DEBUG]   - ${f}`));
} catch (e) {
  console.error(`[DEBUG] ERROR: Could not read integration test directory: ${integrationTestDir}`);
  console.error(`[DEBUG] Error: ${e instanceof Error ? e.message : String(e)}`);
}

// Define a type that includes the 'test' property from Vitest's config.
// This allows us to destructure it in a type-safe way without using 'as any'.
type ViteConfigWithTest = UserConfig & { test?: UserConfig['test'] };

const { test: _unusedTest, ...baseViteConfig } = viteConfig as ViteConfigWithTest;
console.error('[DEBUG] Merging with base vite config, but excluding its "test" configuration.');

console.error('\n[DEBUG] --- INTEGRATION CONFIG SETUP ---');
// Use _unusedTest to satisfy linter
console.error(`[DEBUG] Stripped "test" config. Original test config existed: ${!!_unusedTest}`);
// Use the 'in' operator for a type-safe property check instead of casting to 'any'.
console.error('[DEBUG] Does baseViteConfig have "test"?', 'test' in baseViteConfig);
console.error('[DEBUG] Base vite config keys:', Object.keys(baseViteConfig));

/**
 * This configuration is specifically for integration tests.
 * It MERGES with the main vite.config.ts to inherit plugins and aliases,
 * then overrides the test-specific settings for a Node.js environment.
 */
const finalConfig = mergeConfig(
  baseViteConfig,
  defineConfig({
    test: {
      // Override settings from the main config for this specific test project.
      name: 'integration',
      environment: 'node',
      // Point specifically to the new integration tests directory.
      // This pattern will match any test file inside `src/tests/integration/`.
      include: ['src/tests/integration/**/*.test.{ts,tsx}'],
      // CRITICAL: We must override the `exclude` property from the base vite.config.ts.
      // Otherwise, the inherited `exclude` rule will prevent any integration tests from running.
      // Setting it to an empty array removes all exclusion rules for this project.
      exclude: [],
      // Fix: Set environment variables to ensure generated URLs pass validation
      env: {
        NODE_ENV: 'test',
        BASE_URL: 'https://example.com', // Use a standard domain to pass strict URL validation
        FRONTEND_URL: 'https://example.com',
        // Use a dedicated test port (3099) to avoid conflicts with production servers
        // that might be running on port 3000 or 3001
        TEST_PORT: '3099',
        VITE_API_BASE_URL: 'http://localhost:3099/api',
      },
      // This setup script starts the backend server before tests run.
      globalSetup: './src/tests/setup/integration-global-setup.ts',
      setupFiles: ['./src/tests/setup/global.ts'],
      // The default timeout is 5000ms (5 seconds)
      testTimeout: 60000, // Increased timeout for server startup and API calls, especially AI services.
      hookTimeout: 60000,
      // "singleThread: true" is removed in modern Vitest.
      // Use fileParallelism: false to ensure test files run one by one to prevent port conflicts.
      fileParallelism: false,
      coverage: {
        provider: 'v8',
        // Include 'text' reporter so coverage summary appears after integration tests complete.
        reporter: [['text', { maxCols: 200 }], 'html', 'json-summary', 'json'],
        reportsDirectory: '.coverage/integration',
        reportOnFailure: true, // This ensures the report generates even if tests fail
        clean: true,
      },
    },
  }),
);

console.error('[DEBUG] Integration Final Config - INCLUDE:', finalConfig.test?.include);
console.error('[DEBUG] Integration Final Config - EXCLUDE:', finalConfig.test?.exclude);
console.error('[DEBUG] ----------------------------------\n');

export default finalConfig;
