/**
 * test/editor.test.ts — openInEditor validation + spawn wiring (v0.6).
 *
 * Uses editorCmd='true' (the POSIX no-op that exits 0, ignoring args) so the
 * success path actually spawns a harmless process — never opening a real editor.
 */

import { describe, it, expect, beforeAll, afterAll } from 'vitest'
import fs from 'node:fs/promises'
import os from 'node:os'
import path from 'node:path'
import { openInEditor } from '../src/http/editor.js'
import type { Config } from '../src/types.js'

function cfg(editorCmd: string): Config {
  // Only editorCmd matters here; the rest is filler to satisfy the type.
  return { editorCmd } as unknown as Config
}

let tmpDir: string
let tmpFile: string

beforeAll(async () => {
  tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'editor-test-'))
  tmpFile = path.join(tmpDir, 'a-file.txt')
  await fs.writeFile(tmpFile, 'hi')
})

afterAll(async () => {
  await fs.rm(tmpDir, { recursive: true, force: true })
})

describe('openInEditor — validation', () => {
  it('rejects a missing/empty path with 400', async () => {
    expect((await openInEditor(cfg('true'), undefined)).status).toBe(400)
    expect((await openInEditor(cfg('true'), '')).status).toBe(400)
    expect((await openInEditor(cfg('true'), '   ')).status).toBe(400)
  })

  it('rejects a non-string path with 400', async () => {
    expect((await openInEditor(cfg('true'), 123)).status).toBe(400)
    expect((await openInEditor(cfg('true'), { path: '/x' })).status).toBe(400)
  })

  it('rejects a relative path with 400', async () => {
    const r = await openInEditor(cfg('true'), 'relative/dir')
    expect(r.ok).toBe(false)
    expect(r.status).toBe(400)
  })

  it('returns 404 for a non-existent absolute path', async () => {
    const r = await openInEditor(cfg('true'), path.join(tmpDir, 'does-not-exist'))
    expect(r.status).toBe(404)
  })

  it('returns 400 when the path is a file, not a directory', async () => {
    const r = await openInEditor(cfg('true'), tmpFile)
    expect(r.status).toBe(400)
  })
})

describe('openInEditor — launch', () => {
  it('spawns the editor for a valid directory (204)', async () => {
    const r = await openInEditor(cfg('true'), tmpDir)
    expect(r.ok).toBe(true)
    expect(r.status).toBe(204)
  })
})
