#!/bin/bash

set -e

echo "=========================================="
echo "ShopCall.ai Edge Functions JWT Fix"
echo "=========================================="
echo ""

# Check if npm is installed
if ! command -v npm &> /dev/null; then
    echo "Error: npm is not installed. Please install Node.js and npm first."
    exit 1
fi

# Install Supabase CLI
echo "Step 1: Installing Supabase CLI..."
npm install -g supabase
echo "✓ Supabase CLI installed"
echo ""

# Login to Supabase
echo "Step 2: Login to Supabase"
echo "Your browser will open. Please login with your Supabase account."
echo ""
supabase login
echo "✓ Logged in successfully"
echo ""

# Navigate to project directory
cd /data/shopcall

# Link to project
echo "Step 3: Linking to your Supabase project..."
supabase link --project-ref ztklqodcdjeqpsvhlpud
echo "✓ Project linked"
echo ""

# Deploy functions with JWT verification disabled
echo "Step 4: Deploying Edge Functions with JWT verification disabled..."
echo ""

echo "Deploying auth function..."
supabase functions deploy auth --no-verify-jwt
echo "✓ auth function deployed"
echo ""

echo "Deploying shopify-oauth function..."
supabase functions deploy shopify-oauth --no-verify-jwt
echo "✓ shopify-oauth function deployed"
echo ""

echo "Deploying woocommerce-oauth function..."
supabase functions deploy woocommerce-oauth --no-verify-jwt
echo "✓ woocommerce-oauth function deployed"
echo ""

echo "Deploying gdpr-webhooks function..."
supabase functions deploy gdpr-webhooks --no-verify-jwt
echo "✓ gdpr-webhooks function deployed"
echo ""

echo "=========================================="
echo "✓ All functions deployed successfully!"
echo "=========================================="
echo ""
echo "Next steps:"
echo "1. Visit https://shopcall.ai/signup"
echo "2. Try registering a new account"
echo "3. You should receive an OTP email"
echo ""
echo "If you still encounter issues, check the logs at:"
echo "https://supabase.com/dashboard/project/ztklqodcdjeqpsvhlpud/logs/edge-functions"
echo ""
