// Workaround for @nuxt/ui v4 import protection issue
// This is a temporary fix until @nuxt/ui properly handles ssr: false

import type { Plugin } from 'vite'
import { fileURLToPath } from 'url'
import { dirname, resolve } from 'path'

const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)
const emptyModulePath = resolve(__dirname, '.nuxt-stubs/empty.mjs')

export function disableImportProtection(): Plugin {
  return {
    name: 'disable-import-protection-for-nuxt-ui',
    enforce: 'pre',
    resolveId(id, importer) {
      // Server-only packages that should be stubbed for client bundle
      const serverPackages = [
        '@nuxt/kit',
        '@tailwindcss/node',
        '@tailwindcss/oxide',
        'jiti'
      ]

      for (const pkg of serverPackages) {
        if (id === pkg || id.startsWith(pkg + '/')) {
          return emptyModulePath
        }
      }

      // Stub .node binary files
      if (id.endsWith('.node')) {
        return emptyModulePath
      }

      // Stub Node.js built-in modules for client bundle
      const nodeModules = ['fs', 'path', 'url', 'fs/promises']
      const nodePrefix = ['node:url', 'node:module', 'node:fs', 'node:path']

      if (nodeModules.includes(id) || nodePrefix.includes(id) || id.startsWith('node:')) {
        return emptyModulePath
      }
    }
  }
}
