import crypto from 'crypto';

const IV_LENGTH = 16;

/**
 * AI_ENCRYPTION_KEY 환경변수에서 암호화 키를 가져온다.
 * 런타임 시 환경변수가 미설정이면 에러를 throw한다.
 * (빌드 타임에는 모듈 로드 시 throw하지 않도록 lazy 평가)
 */
function getEncryptionKey(): string {
    const key = process.env.AI_ENCRYPTION_KEY;
    if (!key) {
        throw new Error('AI_ENCRYPTION_KEY environment variable is required. Do not use default or fallback keys.');
    }
    if (Buffer.from(key).length !== 32) {
        throw new Error(`AI_ENCRYPTION_KEY must be 32 bytes. Current length: ${Buffer.from(key).length}. Please set AI_ENCRYPTION_KEY in environment variables.`);
    }
    return key;
}

export function encrypt(text: string): string {
    const key = getEncryptionKey();
    const iv = crypto.randomBytes(IV_LENGTH);
    const cipher = crypto.createCipheriv('aes-256-gcm', Buffer.from(key), iv);
    const encrypted = Buffer.concat([cipher.update(text, 'utf8'), cipher.final()]);
    const tag = cipher.getAuthTag();
    return iv.toString('hex') + ':' + tag.toString('hex') + ':' + encrypted.toString('hex');
}

export function decrypt(text: string): string {
    const key = getEncryptionKey();
    const textParts = text.split(':');
    const iv = Buffer.from(textParts.shift()!, 'hex');
    const tag = Buffer.from(textParts.shift()!, 'hex');
    const encryptedText = Buffer.from(textParts.join(':'), 'hex');
    const decipher = crypto.createDecipheriv('aes-256-gcm', Buffer.from(key), iv);
    decipher.setAuthTag(tag);
    const decrypted = Buffer.concat([decipher.update(encryptedText), decipher.final()]);
    return decrypted.toString('utf8');
}
