import { readdirSync, readFileSync } from 'node:fs'
import { join } from 'node:path'
import { describe, expect, it } from 'vitest'

const SRC = join(__dirname)
const FORBIDDEN = [
  '@platform-modules/commerce-cart/store-db', // browser-unsafe (db/IO)
  'applyToCart',                              // server-only (pulls a CartStore)
]

function srcFiles(dir: string): string[] {
  return readdirSync(dir, { withFileTypes: true }).flatMap((e) => {
    const p = join(dir, e.name)
    if (e.isDirectory()) return srcFiles(p)
    return /\.(ts|tsx)$/.test(e.name) && !/\.test\.(ts|tsx)$/.test(e.name) ? [p] : []
  })
}

describe('no server-only imports leak into the browser sibling (§7 bundle guard)', () => {
  it('no src file imports store-db / applyToCart', () => {
    const offenders: string[] = []
    for (const f of srcFiles(SRC)) {
      const text = readFileSync(f, 'utf8')
      for (const line of text.split('\n')) {
        const trimmed = line.trim()
        if (!trimmed.startsWith('import') && !/\bfrom\s+['"]/.test(trimmed)) continue
        for (const token of FORBIDDEN) {
          if (line.includes(token)) offenders.push(`${f} → ${token}`)
        }
      }
    }
    expect(offenders, offenders.join('\n')).toEqual([])
  })
})