import path from 'node:path'
import { fileURLToPath } from 'node:url'
import react from '@vitejs/plugin-react'
import { parseCLI, startVitest } from 'vitest/node'

const __dirname = path.dirname(fileURLToPath(import.meta.url))
const root = path.resolve(__dirname, '..')

process.env.NODE_ENV = 'test'

const { filter, options } = parseCLI(['vitest', ...process.argv.slice(2)])
const { coverage: coverageOptions, ...cliOptions } = options

const baseCoverage = {
  provider: 'v8',
  reporter: ['text', 'json', 'html'],
  include: ['src/**/*.{ts,tsx}'],
  exclude: [
    'src/**/*.d.ts',
    'src/**/*.interface.ts',
    'src/test/**',
    'src/main.tsx',
    'src/vite-env.d.ts',
  ],
}

function resolveCoverageConfig(option) {
  if (!option) {
    return {
      ...baseCoverage,
      enabled: false,
    }
  }

  if (option === true) {
    return {
      ...baseCoverage,
      enabled: true,
    }
  }

  return {
    ...baseCoverage,
    ...option,
    enabled: option.enabled ?? true,
  }
}

const ctx = await startVitest(
  'test',
  filter,
  {
    ...cliOptions,
    root,
    config: false,
    globals: true,
    environment: 'jsdom',
    setupFiles: ['./src/test/setup.ts'],
    include: ['src/**/*.{test,spec}.{js,ts,jsx,tsx}'],
    coverage: resolveCoverageConfig(coverageOptions),
    pool: cliOptions.pool ?? 'threads',
    fileParallelism: cliOptions.fileParallelism ?? false,
    maxWorkers: cliOptions.maxWorkers ?? 1,
    testTimeout: cliOptions.testTimeout ?? 10000,
    hookTimeout: cliOptions.hookTimeout ?? 10000,
    clearMocks: true,
  },
  {
    plugins: [react()],
    resolve: {
      preserveSymlinks: true,
      alias: {
        '@': path.resolve(root, 'src'),
      },
    },
  },
)

if (!ctx?.shouldKeepServer()) {
  await ctx?.exit()
}
