import { defineConfig } from 'tsdown'
import { argv } from '../../scripts/tsdown-args.mjs'

/** @import {Options} from 'tsdown' */

const sharedExternal = [
  /.*\/shared\/index\.js$/,
]

const clientExternal = [
  ...sharedExternal,
  /^@internal/,
  /.*\.vue$/,
  /.*\.css$/,
]

export default defineConfig(() => {
  /** @type {Options} */
  const DEFAULT_OPTIONS = {
    dts: true,
    sourcemap: false,
    format: 'esm',
    fixedExtension: false,
  }

  /** @type {Options[]} */
  const options = []

  // shared
  options.push({
    ...DEFAULT_OPTIONS,
    entry: ['./src/shared/index.ts'],
    outDir: './lib/shared',
  })

  if (argv.node) {
    options.push({
      ...DEFAULT_OPTIONS,
      entry: ['./src/node/index.ts'],
      outDir: './lib/node',
      external: sharedExternal,
      target: 'node20.6.0',
    })
  }

  if (argv.client) {
    options.push(...[
      // client/utils/index.js
      {
        ...DEFAULT_OPTIONS,
        entry: ['./src/client/utils/index.ts'],
        outDir: './lib/client/utils',
        external: clientExternal,
      },
      // client/composables/index.js
      {
        ...DEFAULT_OPTIONS,
        entry: ['./src/client/composables/index.ts'],
        outDir: './lib/client/composables',
        external: clientExternal,
      },
      // client/config.js
      {
        ...DEFAULT_OPTIONS,
        entry: ['./src/client/config.ts'],
        outDir: './lib/client',
        external: clientExternal,
        dts: false,
      },
      // client/index.js
      {
        ...DEFAULT_OPTIONS,
        entry: ['./src/client/index.ts'],
        outDir: './lib/client',
        external: [
          ...clientExternal,
          './composables/index.js',
        ],
      },
    ])
  }

  return options
})
