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

describe('render-same-origin-deployment CLI', () => {
  it('writes resolved systemd and nginx files for a concrete checkout root', () => {
    const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'hypertwist-render-cli-'))
    const systemdOut = path.join(tempDir, 'hypertwist.service')
    const nginxOut = path.join(tempDir, 'hypertwist.conf')

    try {
      const result = spawnSync(
        process.execPath,
        [
          renderScript,
          '--checkout-root',
          '/srv/hypertwist/current',
          '--service-user',
          'deploy',
          '--service-group',
          'deploy',
          '--server-names',
          'hypertwist.app,www.hypertwist.app',
          '--systemd-out',
          systemdOut,
          '--nginx-out',
          nginxOut,
        ],
        {
          cwd: websiteRoot,
          encoding: 'utf8',
        },
      )

      expect(result.status).toBe(0)
      expect(result.stderr).toBe('')
      expect(fs.readFileSync(systemdOut, 'utf8')).toContain('User=deploy')
      expect(fs.readFileSync(nginxOut, 'utf8')).toContain('server_name hypertwist.app www.hypertwist.app;')
    } finally {
      fs.rmSync(tempDir, { recursive: true, force: true })
    }
  })
})
