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-live-deploy.mjs')

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

    fs.writeFileSync(manifestPath, JSON.stringify({
      deploymentTier: 'preview',
      checkoutRoot: '/srv/hypertwist/current',
      publicOrigin: 'https://hypertwist.app',
      supportEmail: 'hello@hypertwist.app',
      publicDocsUrl: 'https://hypertwist.app/resources',
      releaseNotesUrl: 'https://hypertwist.app/changelog',
      correspondingSourceUrl: 'https://git.scriptoriumai.io/scriptoriumadmin/hypertwist',
      openSourceRepoUrl: 'https://git.scriptoriumai.io/scriptoriumadmin/hypertwist',
      operatorCheckoutUrl: '',
      windowsDownloadUrl: '',
      releaseManifestVersion: '',
      windowsRelease: {
        buildId: '',
        sha256: '',
        publishedAt: '',
      },
      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.vpsUser).toBe('root')
      expect(payload.archiveSource).toBe('worktree')
      expect(payload.manifest.server.paddleWebhookSecret).toBe('su***en')
      expect(payload.deployScript).toContain('__HYPERTWIST_LIVE_DEPLOY_SUMMARY__')
    } finally {
      fs.rmSync(tempDir, { recursive: true, force: true })
    }
  })
})
