#!/bin/bash

# Script to update MongoDB Plans via localhost-only API endpoint
# Usage: ./update-plans.sh [port]

PORT=${1:-52428}
API_URL="https://localhost:$PORT/api/Admin/SeedPlans"
PLANS_FILE="$(dirname "$0")/plans.json"

echo "🔧 QR Rapido - Update Plans Script"
echo "=================================="
echo ""
echo "📋 Plans file: $PLANS_FILE"
echo "🌐 API URL: $API_URL"
echo ""

# Check if plans.json exists
if [ ! -f "$PLANS_FILE" ]; then
    echo "❌ Error: plans.json not found at $PLANS_FILE"
    echo ""
    echo "Please create plans.json with your Stripe Price IDs"
    exit 1
fi

# Check if the app is running
echo "🔍 Checking if app is running on port $PORT..."
if ! curl -k -s "https://localhost:$PORT/health" > /dev/null 2>&1; then
    echo "❌ Error: App not responding on https://localhost:$PORT"
    echo ""
    echo "Please start the app first:"
    echo "  dotnet run"
    exit 1
fi

echo "✅ App is running"
echo ""

# Send request
echo "📤 Sending plans to API..."
response=$(curl -k -s -w "\n%{http_code}" \
    -X POST \
    -H "Content-Type: application/json" \
    -d @"$PLANS_FILE" \
    "$API_URL")

http_code=$(echo "$response" | tail -n1)
body=$(echo "$response" | sed '$d')

echo ""

if [ "$http_code" -eq 200 ]; then
    echo "✅ Success! Plans updated in MongoDB"
    echo ""
    echo "$body" | jq '.' 2>/dev/null || echo "$body"
else
    echo "❌ Error! HTTP Status: $http_code"
    echo ""
    echo "$body"
    exit 1
fi

echo ""
echo "🎉 Done!"
