/// <reference types="node" />
import { existsSync, readdirSync, readFileSync } from 'node:fs'
import { join } from 'node:path'
import { describe, expect, it } from 'vitest'

const SRC = join(__dirname)
const PKG_ROOT = join(__dirname, '..')
const FORBIDDEN = [
  '@platform-modules/db',
  '@platform-modules/commerce-reviews/schema',
  'submitReview',
  'replyToReview',
  'moderateReview',
  'getRatingAggregate',
  'listReviews',
  'pushReviewsSchema',
  'drizzle-orm',
  'node:',
]

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] : []
  })
}

function scanImportLines(files: string[]): string[] {
  const offenders: string[] = []
  for (const f of files) {
    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}`)
      }
    }
  }
  return offenders
}

function distOffenders(text: string, label: string): string[] {
  const offenders: string[] = []
  for (const line of text.split('\n')) {
    const trimmed = line.trim()
    if (!trimmed.startsWith('import') && !/\bfrom\s+['"]/.test(trimmed) && !trimmed.includes('require(')) continue
    for (const token of FORBIDDEN) {
      if (line.includes(token)) offenders.push(`${label} → ${token}`)
    }
  }
  for (const token of ['@platform-modules/db', '@platform-modules/commerce-reviews/schema', 'drizzle-orm', 'node:']) {
    if (text.includes(token)) offenders.push(`${label} → ${token}`)
  }
  return offenders
}

describe('no server-only imports leak into the browser sibling (§7 bundle guard)', () => {
  it('no src file imports server-only symbols', () => {
    const offenders = scanImportLines(srcFiles(SRC))
    expect(offenders, offenders.join('\n')).toEqual([])
  })

  it('built dist bundle carries no server-only imports when dist is present', () => {
    const distJs = join(PKG_ROOT, 'dist', 'index.js')
    if (!existsSync(distJs)) return

    const js = readFileSync(distJs, 'utf8')
    const offenders = distOffenders(js, 'dist/index.js')
    expect(offenders, offenders.join('\n')).toEqual([])
  })
})
