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 scriptPath = path.join(websiteRoot, 'scripts', 'run-vps-same-origin-staging-proof.mjs')

describe('run-vps-same-origin-staging-proof CLI', () => {
  it('supports dry-run json output with a sanitized manifest preview', () => {
    const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'hypertwist-staging-proof-cli-'))
    const manifestPath = path.join(tempDir, 'bundle.json')
    const identityFile = path.join(tempDir, 'id_ed25519')

    fs.writeFileSync(manifestPath, JSON.stringify({
      checkoutRoot: '/srv/hypertwist/current',
      publicOrigin: 'https://hypertwist.app',
      supportEmail: 'hello@hypertwist.app',
      publicDocsUrl: 'https://hypertwist.app/docs',
      releaseNotesUrl: 'https://hypertwist.app/changelog',
      correspondingSourceUrl: 'https://git.scriptoriumai.io/scriptoriumadmin/hypertwist',
      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',
      windowsRelease: {
        buildId: 'win64-1000',
        sha256: 'abc123',
        publishedAt: '2026-06-22T00:00:00.000Z',
      },
      server: {
        paddleWebhookSecret: 'super-secret-token',
      },
    }, null, 2))
    fs.writeFileSync(identityFile, 'fake-key', 'utf8')

    try {
      const result = spawnSync(
        process.execPath,
        [
          scriptPath,
          '--manifest',
          manifestPath,
          '--identity-file',
          identityFile,
          '--archive-source',
          'worktree',
          '--dry-run',
          '--json',
        ],
        {
          cwd: websiteRoot,
          encoding: 'utf8',
        },
      )

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

      const payload = JSON.parse(result.stdout)
      expect(payload.vpsHost).toBe('212.227.13.220')
      expect(payload.archiveSource).toBe('worktree')
      expect(payload.port).toBe(3011)
      expect(payload.remoteManifest.server.paddleWebhookSecret).toBe('su***en')
      expect(payload.remoteScript).toContain('__HYPERTWIST_STAGING_SUMMARY__')
    } finally {
      fs.rmSync(tempDir, { recursive: true, force: true })
    }
  })
})
