/**
 * Serialize-and-encrypt for NotificationChannel.config writes.
 *
 * Every channel-create / channel-update API route should call
 * serializeChannelConfig(input) instead of stringifying themselves.
 * Today's value: AES-256-GCM envelope (v1). The helper keeps the
 * "encrypt on write" rule in one place so a route author can't forget.
 *
 * Read paths continue to use decryptIfNeeded() which handles both v1
 * envelopes and legacy plaintext rows (until the migration script
 * scripts/encrypt-existing-channels.ts has converted them).
 */
import { encrypt } from '@/lib/crypto/secret-vault';

export function serializeChannelConfig(config: unknown): string {
    if (config === null || config === undefined) {
        throw new Error('serializeChannelConfig: config is required');
    }
    const plaintext =
        typeof config === 'string' ? config : JSON.stringify(config);
    if (plaintext.length === 0) {
        throw new Error('serializeChannelConfig: refusing to encrypt empty config');
    }
    return encrypt(plaintext);
}
