/**
 * Post-build fix: Pinia CJS (pinia.prod.cjs) fait require('vue').
 * Rollup convertit ça en `import require$$0 from 'vue'` (default import).
 * Vue 3 n'a pas de default export en ESM → crash Node 22+.
 *
 * Ce script remplace le default import par un namespace import valide.
 */
import { readFileSync, writeFileSync, existsSync } from 'node:fs'

const file = '.output/server/chunks/build/server.mjs'

if (!existsSync(file)) {
  console.log('[fix-esm] server.mjs not found, skipping')
  process.exit(0)
}

let code = readFileSync(file, 'utf-8')

// Pattern: import require$$0, { defineComponent, inject, ... } from 'vue'
// → import * as require$$0 from 'vue'; import { defineComponent, ... } from 'vue'
const re = /import\s+(require\$\$\d+)\s*,\s*\{([^}]+)\}\s*from\s*'vue'/g
let patched = false

code = code.replace(re, (match, varName, namedStr) => {
  patched = true
  const names = namedStr.split(',').map(n => n.trim()).filter(Boolean)
  return `import * as ${varName} from 'vue'; import { ${names.join(', ')} } from 'vue'`
})

if (patched) {
  writeFileSync(file, code)
  console.log('[fix-esm] Patched default import from vue in server.mjs')
} else {
  console.log('[fix-esm] No default import found, nothing to patch')
}
