#!/bin/bash

echo "Testing CSV Booking Creation"
echo "=============================="

API_URL="http://localhost:4000/api/v1"

# Step 1: Login
echo "Step 1: Login..."
LOGIN_RESPONSE=$(curl -s -X POST "${API_URL}/auth/login" \
  -H "Content-Type: application/json" \
  -d '{"email":"admin@xpeditis.com","password":"Admin123!"}')

TOKEN=$(echo "$LOGIN_RESPONSE" | grep -o '"accessToken":"[^"]*"' | cut -d'"' -f4)

if [ -z "$TOKEN" ]; then
  echo "ERROR: Login failed"
  echo "$LOGIN_RESPONSE"
  exit 1
fi

echo "SUCCESS: Token obtained"
echo ""

# Step 2: Create test file
echo "Step 2: Creating test document..."
TEST_FILE="/tmp/test-bol.txt"
echo "Bill of Lading - Test Document" > "$TEST_FILE"
echo "Date: $(date)" >> "$TEST_FILE"
echo "Origin: NLRTM" >> "$TEST_FILE"
echo "Destination: USNYC" >> "$TEST_FILE"

echo "SUCCESS: Test file created at $TEST_FILE"
echo ""

# Step 3: Create booking
echo "Step 3: Creating CSV booking..."
RESPONSE=$(curl -s -w "\nSTATUS:%{http_code}" -X POST "${API_URL}/csv-bookings" \
  -H "Authorization: Bearer ${TOKEN}" \
  -F "carrierName=Test Carrier" \
  -F "carrierEmail=carrier@test.com" \
  -F "origin=NLRTM" \
  -F "destination=USNYC" \
  -F "volumeCBM=2.88" \
  -F "weightKG=1500" \
  -F "palletCount=3" \
  -F "priceUSD=4834.44" \
  -F "priceEUR=4834.44" \
  -F "primaryCurrency=USD" \
  -F "transitDays=22" \
  -F "containerType=LCL" \
  -F "notes=Test" \
  -F "documents=@${TEST_FILE}")

STATUS=$(echo "$RESPONSE" | grep "STATUS" | cut -d':' -f2)
BODY=$(echo "$RESPONSE" | sed '/STATUS/d')

echo "HTTP Status: $STATUS"
echo ""
echo "Response:"
echo "$BODY"
echo ""

if [ "$STATUS" = "201" ] || [ "$STATUS" = "200" ]; then
  echo "SUCCESS: Booking created!"
else
  echo "FAILED: Booking creation failed with status $STATUS"
fi

echo ""
echo "Check backend logs:"
tail -50 /tmp/backend-startup.log | grep -i "csv\|booking\|error" | tail -20
