export type E2eeEnvelope = {
  v: 1;
  e2ee: true;
  iv: string;
  alg: "AES-GCM";
  ciphertext: string;
};

export const E2EE_LOCKED_PREVIEW = "🔒 پیام رمزنگاری‌شده";

export function isE2eeEnvelope(content: unknown): content is string {
  if (typeof content !== "string") return false;
  const trimmed = content.trim();
  if (!trimmed.startsWith("{")) return false;
  try {
    const parsed = JSON.parse(trimmed) as Partial<E2eeEnvelope>;
    return Boolean(parsed?.e2ee === true && parsed?.ciphertext && parsed?.iv);
  } catch {
    return false;
  }
}

export function parseEnvelope(content: string): E2eeEnvelope | null {
  if (!isE2eeEnvelope(content)) return null;
  try {
    return JSON.parse(content.trim()) as E2eeEnvelope;
  } catch {
    return null;
  }
}

export function serializeEnvelope(env: E2eeEnvelope): string {
  return JSON.stringify(env);
}
