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

const workflow = readFileSync(new URL('../../../.github/workflows/pr.yml', import.meta.url), 'utf8')
const wrangler = readFileSync(new URL('../wrangler.toml', import.meta.url), 'utf8')

describe('preview Worker config contract', () => {
  it('declares every checked-in binding in generated isolated config', () => {
    const bindings = new Set([
      ...Array.from(wrangler.matchAll(/^binding\s*=\s*"([A-Z0-9_]+)"/gm), (match) => match[1]),
      ...Array.from(wrangler.matchAll(/^name\s*=\s*"([A-Z0-9_]+)"/gm), (match) => match[1]),
    ])
    const missing = [...bindings].filter((binding) => !workflow.includes(`'${binding}'`) && !workflow.includes(`"${binding}"`))
    expect(missing).toEqual([])
  })

  it('rejects production resource IDs in generated preview config', () => {
    const requiredKeys = [
      'hyperdriveId', 'kvNamespaceId', 'storageBucketName', 'receiptsBucketName',
      'invoiceSnapshotsBucketName', 'portalFilesBucketName', 'jobsQueueName',
      'auditQueueName', 'expenseQueueName', 'supportReplyDispatchQueueName',
      'realtimeQueueName', 'vectorizeIndexName',
    ]
    expect(workflow).toContain('PREVIEW_CLOUDFLARE_RESOURCES')
    for (const key of requiredKeys) expect(workflow).toContain(`resources.${key}`)
    expect(workflow).toContain('Object.keys(resources).sort()')
    expect(workflow).toContain('productionValues.has(value)')
    expect(workflow).toContain('checkedInConfig.matchAll(/^namespace_id\\s*=')
    expect(workflow).toMatch(/namespace_id: '9002(?:00[1-5]|10[1-3])'/)
    expect(workflow).not.toMatch(/namespace_id: '(?:100[1-5]|110[1-3])'/)
    expect(workflow).not.toContain('previewSuffix')
    expect(workflow).not.toMatch(/zync-preview-\$\{/)
  })
})
