import { execSync } from 'node:child_process'
import { readFileSync } from 'node:fs'
import { fileURLToPath, URL } from 'node:url'
import { defineConfig, type Plugin } from 'vite'
import vue from '@vitejs/plugin-vue'
import dts from 'vite-plugin-dts'

function resolveReleaseDate(): string {
  try {
    const pkg = JSON.parse(
      readFileSync(fileURLToPath(new URL('./package.json', import.meta.url)), 'utf-8')
    ) as { version: string }
    const tagged = execSync(`git log -1 --format=%cs v${pkg.version}`, {
      encoding: 'utf-8',
      stdio: ['ignore', 'pipe', 'ignore'],
    }).trim()
    if (tagged) return tagged
  } catch {
    /* fall through */
  }
  return new Date().toISOString().slice(0, 10)
}

function docsReleaseDatePlugin(): Plugin {
  const releaseDate = resolveReleaseDate()
  const id = 'virtual:docs-release-date'
  const resolved = '\0' + id
  return {
    name: 'docs-release-date',
    resolveId(source) {
      if (source === id) return resolved
    },
    load(loadId) {
      if (loadId === resolved) {
        return `export const releaseDate = ${JSON.stringify(releaseDate)}\n`
      }
    },
  }
}

export default defineConfig(({ command }) => ({
  plugins: [
    vue(),
    docsReleaseDatePlugin(),
    ...(command === 'build'
      ? [dts({ include: ['src'], insertTypesEntry: true })]
      : []),
  ],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('.', import.meta.url)),
    },
  },
  root: command === 'serve' ? 'playground' : undefined,
  server: {
    host: '0.0.0.0',
    allowedHosts: true,
  },
  preview: {
    host: '0.0.0.0',
    allowedHosts: true,
  },
  ...(command === 'build' && {
    build: {
      lib: {
        entry: fileURLToPath(new URL('src/index.ts', import.meta.url)),
        name: 'TvuDesignSystem',
        fileName: 'tvu-design-system',
      },
      rollupOptions: {
        external: ['vue', 'chart.js', 'vue-chartjs', /^chart\.js\//],
        output: {
          globals: { vue: 'Vue', 'chart.js': 'Chart', 'vue-chartjs': 'VueChartJS' },
          exports: 'named',
        },
      },
      cssCodeSplit: false,
    },
  }),
  test: {
    environment: 'jsdom',
    globals: true,
    root: '.',
    include: ['tests/**/*.{test,spec}.{ts,mts}'],
  },
}))
