#!/bin/bash

echo "=========================================="
echo "Testing TaxCore Flow"
echo "=========================================="
echo ""

# Test 1: Health Check
echo "1. Testing Node.js Service Health..."
HEALTH=$(curl -s http://localhost:3001/health)
echo "Response: $HEALTH"
echo ""

# Test 2: Tax Rates (Node.js → TaxCore → Node.js)
echo "2. Testing Tax Rates Endpoint (Node.js → TaxCore)..."
TAX_RATES=$(curl -s http://localhost:3001/tax-rates)
echo "Response (first 200 chars): ${TAX_RATES:0:200}..."
echo ""

# Test 3: Direct Node.js Sale (Node.js → TaxCore → Node.js)
echo "3. Testing Direct Node.js Sale Endpoint..."
DIRECT_SALE=$(curl -s -X POST http://localhost:3001/sale \
  -H "Content-Type: application/json" \
  -d '{
    "type": "Training",
    "cashier": "Test Cashier",
    "buyerId": "TESTBUYER123",
    "buyerCostCenterId": "CC001",
    "invoiceType": 3,
    "transactionType": "Sale",
    "payment": [
      {
        "paymentType": "CASH",
        "amount": 10.00
      }
    ],
    "items": [
      {
        "labels": ["Test Item"],
        "totalAmount": 10.00,
        "quantity": 1.0,
        "unitPrice": 10.00,
        "name": "Test Product",
        "taxLabels": ["A"]
      }
    ]
  }')
echo "Response (first 300 chars): ${DIRECT_SALE:0:300}..."
echo ""

# Test 4: PHP Proxy Sale (Browser/PHP → Node.js → TaxCore → Node.js → PHP)
echo "4. Testing PHP Proxy to Node.js (Full Flow)..."
PHP_SALE=$(curl -s -X POST http://localhost:8080/api/pos/taxcore \
  -H "Content-Type: application/json" \
  -d '{
    "type": "Training",
    "cashier": "Test Cashier PHP",
    "buyerId": "PHPTEST123",
    "buyerCostCenterId": "CC002",
    "invoiceType": 3,
    "transactionType": "Sale",
    "payment": [
      {
        "paymentType": "CASH",
        "amount": 15.00
      }
    ],
    "items": [
      {
        "labels": ["PHP Test Item"],
        "totalAmount": 15.00,
        "quantity": 1.0,
        "unitPrice": 15.00,
        "name": "PHP Test Product",
        "taxLabels": ["A"]
      }
    ]
  }')
echo "Response (first 300 chars): ${PHP_SALE:0:300}..."
echo ""

echo "=========================================="
echo "Flow Test Complete!"
echo "=========================================="
echo ""
echo "Expected Flow:"
echo "  Browser/POS → PHP (PosController) → Node.js Service → TaxCore API"
echo "  TaxCore API → Node.js Service → PHP → Browser/POS"
echo ""
echo "Check logs:"
echo "  - Node.js logs: docker compose logs -f taxcore-service"
echo "  - TaxCore logs: tail -f logs/taxcore-service.log"
