/// <reference types="vitest/config" />
/// <reference types="vitest" />

import { storybookTest } from '@storybook/addon-vitest/vitest-plugin'
import tailwindcss from '@tailwindcss/vite'
// import { devtools } from '@tanstack/devtools-vite'
import tanstackRouter from '@tanstack/router-plugin/vite'
import react from '@vitejs/plugin-react'

// https://vite.dev/config/
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import { defineConfig } from 'vite'
import { analyzer } from 'vite-bundle-analyzer'
// import basicSsl from '@vitejs/plugin-basic-ssl'
import svgr from 'vite-plugin-svgr'
import tsconfigPaths from 'vite-tsconfig-paths'
const dirname = typeof __dirname === 'undefined' ? path.dirname(fileURLToPath(import.meta.url)) : __dirname

// More info at: https://storybook.js.org/docs/next/writing-tests/integrations/vitest-addon

export default defineConfig({
  server: {
    open: true,
    host: '127.0.0.1',
    port: 3000,
    allowedHosts: ['app.postxl.com', 'host.docker.internal'],
  },
  build: {
    outDir: './dist',
    target: 'esnext',
    sourcemap: true,
    commonjsOptions: {
      // https://stackoverflow.com/a/75981440
      strictRequires: true,
    },
    rollupOptions: {
      output: {
        manualChunks(id: string) {
          // Split large dependencies into separate chunks
          if (id.includes('node_modules')) {
            switch (true) {
              case id.includes('/@tanstack/router-devtools-core/') ||
                id.includes('/@tanstack/react-devtools/') ||
                id.includes('/@tanstack/react-query-devtools/') ||
                id.includes('/@tanstack/react-router-devtools/') ||
                id.includes('/@tanstack/devtools/'):
                return 'tanstack-dev-tools'

              // TanStack Router
              case id.includes('@tanstack/react-router'):
                return 'tanstack-router'

              // TanStack Query + tRPC
              case id.includes('@tanstack/react-query') || id.includes('@trpc/'):
                return 'tanstack-query'

              // zod
              case id.includes('/zod'):
                return 'zod'

              // React core - MUST be together to avoid duplication
              case id.includes('react') || id.includes('react-dom'):
                return 'react-vendor'

              // Glide Data Grid - used in multiple tables
              case id.includes('@glideapps/glide-data-grid'):
                return 'glide-data-grid'

              // Visualization libraries - charts
              case id.includes('@visx/'):
                return 'visx'

              default:
                // All other vendor code
                return 'vendor'
            }
          }
        },
      },
      cache: false,
    },
  },
  plugins: [
    // devtools(),
    tsconfigPaths({
      projects: [path.resolve(__dirname, 'tsconfig.json')],
      // optional but recommended to avoid scanning the whole monorepo
      loose: false,
    }),
    // Please make sure that '@tanstack/router-plugin' is passed before '@vitejs/plugin-react'
    tanstackRouter({
      target: 'react',
      autoCodeSplitting: true,
    }),
    svgr(),
    react(),
    tailwindcss(),
    // basicSsl(), // uncomment to enable https/
    analyzer({
      analyzerMode: 'static',
      openAnalyzer: false,
    }),
  ],
  test: {
    projects: [
      {
        extends: true,
        plugins: [
          // The plugin will run tests for the stories defined in your Storybook config
          // See options at: https://storybook.js.org/docs/writing-tests/vitest-plugin
          storybookTest({
            configDir: path.join(dirname, '.storybook'),
          }),
        ],
        test: {
          name: 'storybook',
          browser: {
            enabled: true,
            headless: true,
            provider: 'playwright',
            instances: [
              {
                browser: 'chromium',
              },
            ],
            // Add browser lifecycle options
            isolate: false,
            fileParallelism: false,
            connectTimeout: 60000,
            // Add more stability options
            viewport: {
              width: 1280,
              height: 720,
            },
          },
          // Deterministic execution helps avoid teardown races
          sequence: { concurrent: false, shuffle: false, hooks: 'stack' },
          setupFiles: ['.storybook/vitest.setup.ts'],
          // Increase timeout configurations
          testTimeout: 60000,
          hookTimeout: 60000,
          // Add retry configuration
          retry: 2,
          // Global test settings
          bail: 0,
          globals: true,
        },
      },
    ],
    coverage: {
      provider: 'v8',
      enabled: true,
      reporter: ['text', 'json', 'html', 'lcov'],
      reportsDirectory: './coverage',
    },
  },
})
