/**
 * AES-256-GCM encryption/decryption for API request/response.
 * Uses Web Crypto API with a shared symmetric key.
 * Note: Web Crypto API is only available in secure contexts (HTTPS or localhost).
 */

const ALGO = 'AES-GCM';
const IV_LENGTH = 12;
const TAG_LENGTH = 128;

let cryptoKey: CryptoKey | null = null;

export function isCryptoAvailable(): boolean {
  return typeof window !== 'undefined' && 
         typeof crypto !== 'undefined' && 
         typeof crypto.subtle !== 'undefined';
}

async function getCryptoKey(): Promise<CryptoKey> {
  if (cryptoKey) return cryptoKey;
  const keyB64 = import.meta.env.VITE_ENCRYPTION_KEY || '';
  if (!keyB64) throw new Error('VITE_ENCRYPTION_KEY not configured');
  
  if (!isCryptoAvailable()) {
    throw new Error('Web Crypto API not available (requires HTTPS or localhost)');
  }
  
  let keyBytes = Uint8Array.from(atob(keyB64), c => c.charCodeAt(0));
  // AES-256 requires exactly 32 bytes — pad or truncate to match backend
  if (keyBytes.length !== 32) {
    const padded = new Uint8Array(32);
    padded.set(keyBytes.slice(0, 32));
    keyBytes = padded;
  }
  cryptoKey = await crypto.subtle.importKey('raw', keyBytes, { name: ALGO }, false, ['encrypt', 'decrypt']);
  return cryptoKey;
}

export async function encrypt(plaintext: string): Promise<string> {
  if (!isCryptoAvailable()) {
    throw new Error('Encryption not available in non-secure context');
  }
  const key = await getCryptoKey();
  const iv = crypto.getRandomValues(new Uint8Array(IV_LENGTH));
  const encoded = new TextEncoder().encode(plaintext);
  const cipherBuf = await crypto.subtle.encrypt({ name: ALGO, iv, tagLength: TAG_LENGTH }, key, encoded);
  const cipherBytes = new Uint8Array(cipherBuf);
  // Prepend IV to ciphertext
  const combined = new Uint8Array(iv.length + cipherBytes.length);
  combined.set(iv);
  combined.set(cipherBytes, iv.length);
  return btoa(String.fromCharCode(...combined));
}

export async function decrypt(cipherB64: string): Promise<string> {
  if (!isCryptoAvailable()) {
    throw new Error('Decryption not available in non-secure context');
  }
  const key = await getCryptoKey();
  const combined = Uint8Array.from(atob(cipherB64), c => c.charCodeAt(0));
  const iv = combined.slice(0, IV_LENGTH);
  const cipherBytes = combined.slice(IV_LENGTH);
  const plainBuf = await crypto.subtle.decrypt({ name: ALGO, iv, tagLength: TAG_LENGTH }, key, cipherBytes);
  return new TextDecoder().decode(plainBuf);
}