import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { spawnSync } from 'node:child_process'
import { fileURLToPath } from 'node:url'

import { describe, expect, it } from 'vitest'

const currentFile = fileURLToPath(import.meta.url)
const websiteRoot = path.resolve(path.dirname(currentFile), '..')
const renderScript = path.join(websiteRoot, 'scripts', 'render-same-origin-bundle.mjs')

describe('render-same-origin-bundle CLI', () => {
  it('writes a validated deployment bundle from a manifest file', () => {
    const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'hypertwist-bundle-cli-'))
    const manifestPath = path.join(tempDir, 'bundle.json')
    const outDir = path.join(tempDir, 'rendered')

    fs.writeFileSync(manifestPath, JSON.stringify({
      checkoutRoot: '/srv/hypertwist/current',
      publicOrigin: 'https://hypertwist.app',
      supportEmail: 'hello@hypertwist.app',
      publicDocsUrl: 'https://docs.hypertwist.app',
      releaseNotesUrl: 'https://notes.hypertwist.app',
      correspondingSourceUrl: 'https://hypertwist.app/open-source/source.zip',
      openSourceRepoUrl: 'https://git.scriptoriumai.io/scriptoriumadmin/hypertwist',
      operatorCheckoutUrl: 'https://buy.paddle.com/operator',
      studioCheckoutUrl: 'https://buy.paddle.com/studio',
      windowsDownloadUrl: 'https://downloads.hypertwist.app/windows.exe',
      releaseManifestVersion: '1.0.0',
      releaseManifestChannel: 'candidate',
      windowsRelease: {
        buildId: 'win64-1000',
        sha256: 'abc123',
        fileSizeBytes: 123456789,
        publishedAt: '2026-06-22T00:00:00.000Z',
      },
      server: {
        paddleWebhookSecret: 'secret',
        paddleProductPlanMap: {
          prod_operator: 'operator',
        },
        paddlePricePlanMap: {
          pri_operator: 'operator',
        },
      },
    }, null, 2))

    try {
      const result = spawnSync(
        process.execPath,
        [
          renderScript,
          '--manifest',
          manifestPath,
          '--out-dir',
          outDir,
          '--summary',
        ],
        {
          cwd: websiteRoot,
          encoding: 'utf8',
        },
      )

      expect(result.status).toBe(0)
      expect(result.stderr).toBe('')

      const summary = JSON.parse(result.stdout)
      expect(summary.validationReport.ok).toBe(true)
      expect(fs.readFileSync(path.join(outDir, 'website.env'), 'utf8')).toContain('VITE_WINDOWS_DOWNLOAD_URL=https://downloads.hypertwist.app/windows.exe')
      expect(fs.readFileSync(path.join(outDir, 'server.env'), 'utf8')).toContain('RELEASE_MANIFEST_VERSION=1.0.0')
      expect(fs.readFileSync(path.join(outDir, 'hypertwist.app.conf'), 'utf8')).toContain('server_name hypertwist.app www.hypertwist.app;')
    } finally {
      fs.rmSync(tempDir, { recursive: true, force: true })
    }
  })
})
