#!/bin/bash

# Trackex MCP Server Deployment Script
# This script helps deploy the MCP server to Cloudflare Workers

set -e

echo "🚀 Trackex MCP Server Deployment"
echo "================================="

# Check if wrangler is installed
if ! command -v wrangler &> /dev/null; then
    echo "❌ Wrangler CLI is not installed. Please install it first:"
    echo "   npm install -g wrangler"
    exit 1
fi

# Check if user is logged in to Cloudflare
if ! wrangler whoami &> /dev/null; then
    echo "🔐 Please log in to Cloudflare first:"
    echo "   wrangler login"
    exit 1
fi

echo "✅ Wrangler CLI is ready"

# Install dependencies
echo "📦 Installing dependencies..."
npm install

# Check if secrets are set
echo "🔑 Checking secrets..."

SECRETS_MISSING=false

if ! wrangler secret list | grep -q "MICROSOFT_CLIENT_ID"; then
    echo "❌ MICROSOFT_CLIENT_ID secret is not set"
    SECRETS_MISSING=true
fi

if ! wrangler secret list | grep -q "MICROSOFT_CLIENT_SECRET"; then
    echo "❌ MICROSOFT_CLIENT_SECRET secret is not set"
    SECRETS_MISSING=true
fi

if ! wrangler secret list | grep -q "MICROSOFT_TENANT_ID"; then
    echo "❌ MICROSOFT_TENANT_ID secret is not set"
    SECRETS_MISSING=true
fi

if [ "$SECRETS_MISSING" = true ]; then
    echo ""
    echo "🔧 Please set the missing secrets:"
    echo "   wrangler secret put MICROSOFT_CLIENT_ID"
    echo "   wrangler secret put MICROSOFT_CLIENT_SECRET"
    echo "   wrangler secret put MICROSOFT_TENANT_ID"
    echo ""
    echo "You can get these values from your Azure AD app registration:"
    echo "   https://portal.azure.com -> Azure Active Directory -> App registrations"
    exit 1
fi

echo "✅ All secrets are configured"

# Run TypeScript compilation check
echo "🔍 Checking TypeScript compilation..."
npx tsc --noEmit

echo "✅ TypeScript compilation successful"

# Deploy to Cloudflare Workers
echo "🚀 Deploying to Cloudflare Workers..."
wrangler deploy

echo ""
echo "✅ Deployment successful!"
echo ""
echo "📋 Next steps:"
echo "1. Note your worker URL from the deployment output above"
echo "2. Update your Azure AD app registration redirect URI to:"
echo "   https://your-worker-domain.workers.dev/auth/callback"
echo "3. Configure Claude.ai with your MCP server:"
echo "   - URL: https://your-worker-domain.workers.dev/mcp"
echo "   - Auth URL: https://your-worker-domain.workers.dev/auth/login"
echo ""
echo "🔗 Test your deployment:"
echo "   curl https://your-worker-domain.workers.dev/health"
echo ""
echo "📚 For more information, see README.md" 