import { describe, it, expect, beforeEach, afterEach } from 'vitest';

describe('encryption', () => {
    const originalEnv = process.env.AI_ENCRYPTION_KEY;

    beforeEach(() => {
        // 32바이트 테스트 키 설정
        process.env.AI_ENCRYPTION_KEY = 'test-encryption-key-32-bytes-ok!';
    });

    afterEach(() => {
        process.env.AI_ENCRYPTION_KEY = originalEnv;
    });

    it('encrypt/decrypt 라운드트립이 동작한다', async () => {
        const { encrypt, decrypt } = await import('@/utils/encryption');
        const plaintext = '테스트 메시지';
        const encrypted = encrypt(plaintext);
        const decrypted = decrypt(encrypted);
        expect(decrypted).toBe(plaintext);
    });

    it('같은 평문을 암호화해도 결과가 다르다 (IV 랜덤)', async () => {
        const { encrypt } = await import('@/utils/encryption');
        const plaintext = '테스트 메시지';
        const enc1 = encrypt(plaintext);
        const enc2 = encrypt(plaintext);
        expect(enc1).not.toBe(enc2);
    });

    it('영문 텍스트 암호화/복호화', async () => {
        const { encrypt, decrypt } = await import('@/utils/encryption');
        const plaintext = 'Hello World';
        expect(decrypt(encrypt(plaintext))).toBe(plaintext);
    });

    it('환경변수 미설정 시 에러를 throw한다', async () => {
        process.env.AI_ENCRYPTION_KEY = '';
        // 모듈 캐시 초기화 필요
        await expect(async () => {
            const mod = await import('@/utils/encryption?t=' + Date.now());
            mod.encrypt('test');
        }).rejects.toThrow();
    });
});
