#!/bin/bash

# Script to initialize and run Stripe CLI webhook forwarding
# Usage: ./stripe-init-webhook.sh --site <site> --port <port>

set -e

# Colors for output
BLUE='\033[0;34m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m' # No Color

# Display banner
echo ""
echo -e "${BLUE}+-----------------------------------------------+${NC}"
echo -e "${BLUE}   ██████╗ ██╗  ██╗██╗██╗      ██████╗ ██╗  ██╗${NC}"
echo -e "${BLUE}  ██╔════╝ ██║  ██║██║██║     ██╔═══██╗██║  ██║${NC}"
echo -e "${BLUE}  ╚█████╗  ███████║██║██║     ██║   ██║███████║${NC}"
echo -e "${BLUE}   ╚═══██╗ ██╔══██║██║██║     ██║   ██║██╔══██║${NC}"
echo -e "${BLUE}  ██████╔╝ ██║  ██║██║███████╗╚██████╔╝██║  ██║${NC}"
echo -e "${BLUE}  ╚═════╝  ╚═╝  ╚═╝╚═╝╚══════╝ ╚═════╝ ╚═╝  ╚═╝${NC}"
echo -e "${BLUE}+-----------------------------------------------+${NC}"
echo -e "${YELLOW}  🚀 Automated Local Stripe Environment${NC}"
echo -e "${YELLOW}  💼 For ERPNext Development${NC}"
echo -e "${BLUE}+-----------------------------------------------+${NC}"
echo ""

# Default values
SITE=""
PORT="8000"

# Parse command line arguments
while [[ $# -gt 0 ]]; do
    case $1 in
        --site)
            SITE="$2"
            shift 2
            ;;
        --port)
            PORT="$2"
            shift 2
            ;;
        -h|--help)
            echo "Usage: $0 --site <site> [--port <port>]"
            echo ""
            echo "Options:"
            echo "  --site    Required. The site domain (e.g., erp.local)"
            echo "  --port    Optional. The port number (default: 8000)"
            echo ""
            echo "Example:"
            echo "  $0 --site erp.local --port 8000"
            exit 0
            ;;
        *)
            echo "Unknown option: $1"
            echo "Use --help for usage information"
            exit 1
            ;;
    esac
done

# Check if required flag is provided
if [ -z "$SITE" ]; then
    echo -e "${RED}❌ Error: --site flag is required${NC}"
    echo "Usage: $0 --site <site> [--port <port>]"
    exit 1
fi

echo -e "${BLUE}🔍 Checking Stripe CLI installation...${NC}"

# Check if Stripe CLI is installed
if ! command -v stripe &> /dev/null; then
    echo -e "${YELLOW}⚠️  Stripe CLI is not installed.${NC}"
    read -p "Would you like to install it now? (y/n) " -n 1 -r
    echo
    
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        echo -e "${BLUE}📦 Installing Stripe CLI...${NC}"
        
        # Add GPG key
        echo -e "${BLUE}🔑 Adding Stripe GPG key...${NC}"
        curl -s https://packages.stripe.dev/api/security/keypair/stripe-cli-gpg/public | gpg --dearmor | sudo tee /usr/share/keyrings/stripe.gpg > /dev/null
        
        # Add repository
        echo -e "${BLUE}📚 Adding Stripe repository...${NC}"
        echo "deb [signed-by=/usr/share/keyrings/stripe.gpg] https://packages.stripe.dev/stripe-cli-debian-local stable main" | sudo tee -a /etc/apt/sources.list.d/stripe.list
        
        # Update and install
        echo -e "${BLUE}🔄 Updating package list...${NC}"
        sudo apt update
        
        echo -e "${BLUE}⬇️  Installing Stripe CLI...${NC}"
        sudo apt install stripe -y
        
        echo -e "${GREEN}✅ Stripe CLI installed successfully!${NC}"
    else
        echo -e "${RED}❌ Installation cancelled. Exiting.${NC}"
        exit 1
    fi
else
    echo -e "${GREEN}✅ Stripe CLI is already installed.${NC}"
fi

# Check if Stripe CLI is authenticated
echo -e "${BLUE}🔐 Checking authentication status...${NC}"
if ! stripe config --list &> /dev/null; then
    echo -e "${YELLOW}⚠️  Stripe CLI is not authenticated.${NC}"
    echo -e "${BLUE}🔑 Please log in to your Stripe account...${NC}"
    stripe login --interactive
else
    # Try to verify authentication by running a simple command
    if stripe config --list | grep -q "test_mode_api_key"; then
        echo -e "${GREEN}✅ Stripe CLI is authenticated.${NC}"
    else
        echo -e "${YELLOW}⚠️  Stripe CLI authentication may be invalid.${NC}"
        echo -e "${BLUE}🔑 Please log in to your Stripe account...${NC}"
        stripe login --interactive
    fi
fi

# Start Docker containers
echo ""
echo -e "${BLUE}🐳 Starting Docker containers...${NC}"
docker compose -f docker-compose.local.yaml up -d

# Cleanup function to run on exit
cleanup() {
    echo ""
    echo -e "${YELLOW}🛑 Shutting down...${NC}"
    echo -e "${BLUE}🐳 Stopping Docker containers...${NC}"
    docker compose -f docker-compose.local.yaml down
    echo -e "${GREEN}✨ Cleanup complete. Goodbye!${NC}"
    exit 0
}

# Trap Ctrl+C (SIGINT) and termination signals
trap cleanup SIGINT SIGTERM EXIT

# Start listening for webhooks
WEBHOOK_URL="http://${SITE}:${PORT}/api/method/custom_ui.api.public.payments.stripe_webhook"
echo ""
echo -e "${GREEN}🎧 Starting Stripe webhook listener...${NC}"
echo -e "${BLUE}📡 Forwarding to: ${YELLOW}$WEBHOOK_URL${NC}"
echo ""
echo -e "${YELLOW}⌨️  Press Ctrl+C to stop${NC}"
echo ""

stripe listen --forward-to "$WEBHOOK_URL"
