#!/bin/bash

# Star ERP 整合 API 手動測試腳本
# 用途：手動驗證商品同步、POS 訂單、販賣機訂單 API

# --- 設定區 ---
BASE_URL=${1:-"http://localhost:8081"}
TOKEN=${2:-"YOUR_TOKEN_HERE"}
TENANT_DOMAIN="localhost"

echo "=== Star ERP Integration API Test ==="
echo "Target URL: $BASE_URL"
echo "Tenant Domain: $TENANT_DOMAIN"
echo ""

# 顏色定義
GREEN='\033[0;32m'
RED='\033[0;31m'
NC='\033[0m'

# 輔助函式：執行 curl
function call_api() {
    local method=$1
    local path=$2
    local data=$3
    local title=$4

    echo -e "Testing: ${GREEN}$title${NC} ($path)"
    
    curl -s -X "$method" "$BASE_URL$path" \
        -H "X-Tenant-Domain: $TENANT_DOMAIN" \
        -H "Authorization: Bearer $TOKEN" \
        -H "Accept: application/json" \
        -H "Content-Type: application/json" \
        -d "$data" | jq .

    echo -e "-----------------------------------\n"
}

# 1. 商品同步 (Upsert)
PRODUCT_ID="TEST-AUTO-$(date +%s)"
call_api "POST" "/api/v1/integration/products/upsert" "{
    \"external_pos_id\": \"$PRODUCT_ID\",
    \"name\": \"自動測試商品 $(date +%H%M%S)\",
    \"price\": 150,
    \"barcode\": \"690123456789\",
    \"category\": \"飲品\",
    \"cost_price\": 80
}" "Product Upsert"

# 2. POS 訂單同步
call_api "POST" "/api/v1/integration/orders" "{
    \"external_order_id\": \"POS-AUTO-$(date +%s)\",
    \"status\": \"completed\",
    \"payment_method\": \"cash\",
    \"sold_at\": \"$(date -Iseconds)\",
    \"warehouse_id\": 2,
    \"items\": [
        {
            \"pos_product_id\": \"TEST-FINAL-VERIFY\",
            \"qty\": 1,
            \"price\": 100
        }
    ]
}" "POS Order Sync"

# 3. 販賣機訂單同步
call_api "POST" "/api/v1/integration/vending/orders" "{
    \"external_order_id\": \"VEND-AUTO-$(date +%s)\",
    \"machine_id\": \"Vending-Machine-Test-01\",
    \"payment_method\": \"line_pay\",
    \"sold_at\": \"$(date -Iseconds)\",
    \"warehouse_id\": 2,
    \"items\": [
        {
            \"product_code\": \"FINAL-OK\",
            \"qty\": 2,
            \"price\": 50
        }
    ]
}" "Vending Machine Order Sync"

echo "Test Completed."
