/**
 * A7 regression: DeveloperLogEncryptor — no dev-key fallback
 * Bug: constructor fell back to 'dev-key' when no key provided, producing weak encryption.
 * Fix: throws Error if no key is available.
 */

import { describe, it, expect } from 'bun:test'
import { DeveloperLogEncryptor } from '../../src/logging/DeveloperLogEncryptor.js'
import { join } from 'path'
import { tmpdir } from 'os'

describe('A7: DeveloperLogEncryptor no dev-key fallback', () => {
  it('throws when no key is provided and env var is unset', () => {
    const orig = process.env.AIRCODING_PROJECT_KEY
    delete process.env.AIRCODING_PROJECT_KEY

    try {
      expect(() => {
        new DeveloperLogEncryptor(join(tmpdir(), 'test-air-no-key'))
      }).toThrow()
    } finally {
      if (orig !== undefined) {
        process.env.AIRCODING_PROJECT_KEY = orig
      }
    }
  })

  it('succeeds when explicit key is provided', () => {
    expect(() => {
      new DeveloperLogEncryptor(join(tmpdir(), 'test-air-with-key'), 'test-key-123')
    }).not.toThrow()
  })

  it('encrypts and decrypts round-trip correctly', () => {
    const path = join(tmpdir(), 'test-air-roundtrip')
    const encryptor = new DeveloperLogEncryptor(path, 'roundtrip-test-key')

    encryptor.write({ level: 'debug', message: 'test entry' })
    const entries = encryptor.read()

    expect(entries.length).toBeGreaterThan(0)
    const last = entries[entries.length - 1]
    expect(last.message).toBe('test entry')
    expect(last.level).toBe('debug')
  })
})
