#!/bin/bash

# Grubtech Menu Sync - cURL
#
# This example demonstrates how to push menu data to Grubtech API.
#
# Prerequisites:
# - curl command-line tool
# - jq (for JSON parsing, optional)
# - Valid access token from authentication
#
# Replace the following placeholders:
# - {{AUTH_TOKEN}}: Access token from authentication step
# - {{MENU_DATA}}: Your menu data in the required format

AUTH_TOKEN="{{AUTH_TOKEN}}"
BASE_URL="https://api.staging.grubtech.io"

# Example menu data (replace with your actual menu)
MENU_DATA='{
  "name": "Restaurant Menu",
  "description": "Main menu with categories and items",
  "categories": [
    {
      "id": "cat-1",
      "name": "Appetizers",
      "description": "Start your meal right",
      "sortOrder": 1,
      "items": [
        {
          "id": "item-1",
          "name": "Spring Rolls",
          "description": "Crispy vegetable spring rolls",
          "price": 8.99,
          "available": true,
          "modifiers": [
            {
              "id": "mod-1",
              "name": "Extra Sauce",
              "price": 1.50,
              "available": true
            }
          ]
        }
      ]
    },
    {
      "id": "cat-2",
      "name": "Main Courses",
      "description": "Delicious entrees",
      "sortOrder": 2,
      "items": [
        {
          "id": "item-2",
          "name": "Grilled Chicken",
          "description": "Tender chicken with herbs",
          "price": 15.99,
          "available": true,
          "modifiers": []
        }
      ]
    }
  ]
}'

# Push menu data to Grubtech API
create_menu() {
    echo "Creating menu in Grubtech..."

    # Make menu creation request
    RESPONSE=$(curl -s -w "\n%{http_code}" -X POST \
        "${BASE_URL}/v1/menus" \
        -H "Authorization: Bearer ${AUTH_TOKEN}" \
        -H "Content-Type: application/json" \
        -d "${MENU_DATA}")

    # Extract HTTP status code and body
    HTTP_CODE=$(echo "$RESPONSE" | tail -n 1)
    BODY=$(echo "$RESPONSE" | sed '$d')

    # Check for errors
    if [ "$HTTP_CODE" -ne 200 ] && [ "$HTTP_CODE" -ne 201 ]; then
        echo "❌ Menu creation failed: HTTP $HTTP_CODE"
        echo "Response: $BODY"
        return 1
    fi

    # Extract menu ID from response
    if command -v jq &> /dev/null; then
        MENU_ID=$(echo "$BODY" | jq -r '.menuId')
        STATUS=$(echo "$BODY" | jq -r '.status')

        echo "✅ Menu created successfully!"
        echo "Menu ID: ${MENU_ID}"
        echo "Status: ${STATUS}"
    else
        # Fallback: manual parsing
        MENU_ID=$(echo "$BODY" | grep -o '"menuId":"[^"]*' | cut -d'"' -f4)
        echo "✅ Menu created successfully!"
        echo "Menu ID: ${MENU_ID}"
        echo "Note: Install jq for better JSON parsing"
    fi

    echo "$MENU_ID"
}

# Update existing menu
update_menu() {
    local MENU_ID=$1

    echo "Updating menu ${MENU_ID}..."

    curl -s -X PUT \
        "${BASE_URL}/v1/menus/${MENU_ID}" \
        -H "Authorization: Bearer ${AUTH_TOKEN}" \
        -H "Content-Type: application/json" \
        -d "${MENU_DATA}"

    if [ $? -eq 0 ]; then
        echo "✅ Menu updated successfully!"
    else
        echo "❌ Menu update failed"
        return 1
    fi
}

# Main execution
main() {
    # Create menu
    MENU_ID=$(create_menu)

    if [ -z "$MENU_ID" ]; then
        echo "Failed to create menu"
        exit 1
    fi

    echo ""
    echo "Menu created with ID: ${MENU_ID}"

    # Optionally update the menu
    # update_menu "$MENU_ID"
}

# Run main function
main
