#!/bin/bash

# List of functions to update
FUNCTIONS=(
  "oauth-shoprenter-callback"
  "webhooks-shopify"
  "webhook-shoprenter-uninstall"
  "shopify-sync"
  "woocommerce-sync"
  "shoprenter-sync"
  "trigger-sync"
  "shoprenter-scheduled-sync"
  "woocommerce-scheduled-sync"
  "shoprenter-products"
  "shoprenter-orders"
  "shoprenter-customers"
  "get-ai-context"
)

cd /home/claude/shopcall/supabase/functions

for func in "${FUNCTIONS[@]}"; do
  FILE="$func/index.ts"

  if [ -f "$FILE" ]; then
    echo "Updating $FILE..."

    # Check if already has error-handler import
    if grep -q "from '../_shared/error-handler.ts'" "$FILE"; then
      echo "  - Already has error handler import, skipping"
      continue
    fi

    # Add import at the top (after existing imports)
    sed -i '/^import.*from.*supabase-js/a\import { wrapHandler, logError } from '\''../_shared/error-handler.ts'\''' "$FILE"

    # Replace serve(async (req) => { with serve(wrapHandler('function-name', async (req) => {
    sed -i "s/serve(async (req) => {/serve(wrapHandler('$func', async (req) => {/" "$FILE"

    # Remove the outer try-catch block
    # This is complex, so we'll do a simple approach: remove lines with '  } catch (error) {' at the end
    # and the corresponding closing })

    echo "  - Updated $FILE"
  else
    echo "File not found: $FILE"
  fi
done

echo "Done!"
