#!/usr/bin/env bash
# ──────────────────────────────────────────────────────────────────────────────
# create-encryption-keys.sh — Create MEKs for all ByteLyst products in AKV
#
# Prerequisites:
#   1. Azure CLI logged in (az login)
#   2. Key Vault RBAC mode enabled on kv-mywisprai
#   3. Caller has "Key Vault Crypto Officer" role
#
# Usage:
#   ./scripts/create-encryption-keys.sh [--vault-name kv-mywisprai] [--dry-run]
# ──────────────────────────────────────────────────────────────────────────────
set -euo pipefail

VAULT_NAME="${VAULT_NAME:-kv-mywisprai}"
DRY_RUN=false

# Parse args
while [[ $# -gt 0 ]]; do
  case "$1" in
    --vault-name) VAULT_NAME="$2"; shift 2 ;;
    --dry-run)    DRY_RUN=true; shift ;;
    *)            echo "Unknown arg: $1"; exit 1 ;;
  esac
done

# Product MEK names (one per product)
MEKS=(
  "lysnr-mek"
  "mindlyst-mek"
  "jarvisjr-mek"
  "chronomind-mek"
  "nomgap-mek"
  "peakpulse-mek"
  "flowmonk-mek"
  "actiontrail-mek"
  "notelett-mek"
  "localmemgpt-mek"
)

echo "╔═══════════════════════════════════════════════════════════════╗"
echo "║  ByteLyst — Create Master Encryption Keys (MEKs) in AKV     ║"
echo "╠═══════════════════════════════════════════════════════════════╣"
echo "║  Vault:     $VAULT_NAME"
echo "║  Key type:  RSA 4096-bit"
echo "║  Ops:       wrapKey, unwrapKey"
echo "║  Keys:      ${#MEKS[@]}"
echo "║  Dry run:   $DRY_RUN"
echo "╚═══════════════════════════════════════════════════════════════╝"
echo ""

# Step 1: Verify AKV RBAC mode
echo "── Step 1: Verify AKV RBAC mode ─────────────────────────────"
RBAC_ENABLED=$(az keyvault show --name "$VAULT_NAME" --query "properties.enableRbacAuthorization" -o tsv 2>/dev/null || echo "unknown")

if [[ "$RBAC_ENABLED" != "true" ]]; then
  echo "⚠️  WARNING: RBAC is not enabled on $VAULT_NAME (current: $RBAC_ENABLED)"
  echo "   Enable with: az keyvault update --name $VAULT_NAME --enable-rbac-authorization true"
  echo "   ⚠️  This is a BREAKING CHANGE — existing access policies will stop working."
  echo "   Proceed anyway? (y/N)"
  read -r CONFIRM
  if [[ "$CONFIRM" != "y" && "$CONFIRM" != "Y" ]]; then
    echo "Aborted."
    exit 1
  fi
else
  echo "✅ RBAC mode is enabled on $VAULT_NAME"
fi
echo ""

# Step 2: Create MEKs
echo "── Step 2: Create MEKs ──────────────────────────────────────"
CREATED=0
SKIPPED=0
ERRORS=0

for MEK in "${MEKS[@]}"; do
  # Check if key already exists
  EXISTS=$(az keyvault key show --vault-name "$VAULT_NAME" --name "$MEK" --query "key.kid" -o tsv 2>/dev/null || echo "")

  if [[ -n "$EXISTS" ]]; then
    echo "  ⏭️  $MEK — already exists ($EXISTS)"
    SKIPPED=$((SKIPPED + 1))
    continue
  fi

  if $DRY_RUN; then
    echo "  🔍 $MEK — would create (dry run)"
    CREATED=$((CREATED + 1))
    continue
  fi

  echo -n "  🔑 $MEK — creating... "
  if az keyvault key create \
      --vault-name "$VAULT_NAME" \
      --name "$MEK" \
      --kty RSA \
      --size 4096 \
      --ops wrapKey unwrapKey \
      --protection software \
      -o none 2>/dev/null; then
    echo "✅"
    CREATED=$((CREATED + 1))
  else
    echo "❌ FAILED"
    ERRORS=$((ERRORS + 1))
  fi
done

echo ""
echo "── Summary ──────────────────────────────────────────────────"
echo "  Created:  $CREATED"
echo "  Skipped:  $SKIPPED (already exist)"
echo "  Errors:   $ERRORS"
echo ""

if [[ $ERRORS -gt 0 ]]; then
  echo "⚠️  Some keys failed to create. Check AKV access and retry."
  exit 1
fi

echo "✅ Done. MEKs ready for @bytelyst/field-encrypt envelope encryption."
