#!/bin/bash

# Grubtech Order Status Update - cURL
#
# This example demonstrates how to update order status in Grubtech.
#
# 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
# - {{ORDER_ID}}: The Grubtech order ID to update
# - {{NEW_STATUS}}: The new status value (accepted, preparing, ready, delivered, cancelled)

AUTH_TOKEN="{{AUTH_TOKEN}}"
ORDER_ID="{{ORDER_ID}}"
NEW_STATUS="{{NEW_STATUS}}"  # One of: accepted, preparing, ready, delivered, cancelled
BASE_URL="https://api.staging.grubtech.io"

# Valid status values
VALID_STATUSES=("accepted" "preparing" "ready" "delivered" "cancelled")

# Validate status
validate_status() {
    local status=$1
    for valid in "${VALID_STATUSES[@]}"; do
        if [ "$status" == "$valid" ]; then
            return 0
        fi
    done
    echo "❌ Invalid status: $status"
    echo "Valid statuses: ${VALID_STATUSES[*]}"
    return 1
}

# Update order status
update_order_status() {
    local order_id=$1
    local new_status=$2
    local notes=$3

    # Validate status
    if ! validate_status "$new_status"; then
        return 1
    fi

    echo "Updating order ${order_id} to status: ${new_status}"

    # Construct payload
    TIMESTAMP=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
    PAYLOAD=$(cat <<EOF
{
  "orderId": "${order_id}",
  "status": "${new_status}",
  "timestamp": "${TIMESTAMP}",
  "notes": "${notes}"
}
EOF
)

    # Make status update request
    RESPONSE=$(curl -s -w "\n%{http_code}" -X PUT \
        "${BASE_URL}/v1/orders/${order_id}/status" \
        -H "Authorization: Bearer ${AUTH_TOKEN}" \
        -H "Content-Type: application/json" \
        -d "$PAYLOAD")

    # 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 ]; then
        echo "❌ Status update failed: HTTP $HTTP_CODE"
        echo "Response: $BODY"
        return 1
    fi

    # Parse response
    if command -v jq &> /dev/null; then
        ORDER_ID=$(echo "$BODY" | jq -r '.orderId')
        STATUS=$(echo "$BODY" | jq -r '.status')
        UPDATED_AT=$(echo "$BODY" | jq -r '.updatedAt')

        echo "✅ Order status updated successfully!"
        echo "Order ID: ${ORDER_ID}"
        echo "New Status: ${STATUS}"
        echo "Updated At: ${UPDATED_AT}"
    else
        echo "✅ Order status updated successfully!"
        echo "Response: $BODY"
        echo "Note: Install jq for better JSON parsing"
    fi
}

# Example: Full order workflow
order_workflow_example() {
    local order_id=$1

    echo "Running full order workflow for: ${order_id}"
    echo ""

    # Step 1: Accept
    echo "Step 1: Accepting order..."
    update_order_status "$order_id" "accepted" "Order confirmed"
    echo ""

    # Step 2: Preparing
    echo "Step 2: Preparing order..."
    update_order_status "$order_id" "preparing" "Chef started cooking"
    echo ""

    # Step 3: Ready
    echo "Step 3: Order ready..."
    update_order_status "$order_id" "ready" "Order ready for pickup"
    echo ""

    # Step 4: Delivered
    echo "Step 4: Order delivered..."
    update_order_status "$order_id" "delivered" "Order delivered to customer"
    echo ""

    echo "✅ Order workflow completed!"
}

# Main execution
main() {
    # Single status update
    update_order_status "$ORDER_ID" "$NEW_STATUS" "Status update from POS"

    # Or run through full workflow
    # order_workflow_example "$ORDER_ID"
}

# Run main function
main
