#!/bin/bash

# Test script to create a CSV booking and identify errors

set -e

echo "=========================================="
echo "🧪 Test de création de CSV Booking"
echo "=========================================="
echo ""

# Configuration
API_URL="http://localhost:4000/api/v1"
BACKEND_LOG="/tmp/backend-startup.log"

# Couleurs
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Étape 1: Login pour obtenir le JWT token
echo -e "${BLUE}📋 Étape 1: Connexion (obtention du token JWT)${NC}"
echo "----------------------------------------------"

# Utiliser des credentials admin ou de test
LOGIN_RESPONSE=$(curl -s -X POST "${API_URL}/auth/login" \
  -H "Content-Type: application/json" \
  -d '{
    "email": "admin@xpeditis.com",
    "password": "Admin123!"
  }' 2>&1)

echo "Response: ${LOGIN_RESPONSE:0:200}..."

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

if [ -z "$TOKEN" ]; then
  echo -e "${RED}❌ Échec de connexion${NC}"
  echo "Essayez avec d'autres credentials ou créez un utilisateur de test."
  echo "Full response: $LOGIN_RESPONSE"
  exit 1
fi

echo -e "${GREEN}✅ Token obtenu: ${TOKEN:0:30}...${NC}"
echo ""

# Étape 2: Créer un fichier de test
echo -e "${BLUE}📋 Étape 2: Création d'un fichier de test${NC}"
echo "----------------------------------------------"

TEST_FILE="/tmp/test-booking-doc.txt"
cat > "$TEST_FILE" << EOF
BILL OF LADING - TEST DOCUMENT
================================
Booking ID: TEST-$(date +%s)
Origin: NLRTM (Rotterdam)
Destination: USNYC (New York)
Date: $(date)

This is a test document for CSV booking creation.
Weight: 1500 kg
Volume: 2.88 CBM
Pallets: 3

Test completed successfully.
EOF

echo -e "${GREEN}✅ Fichier créé: $TEST_FILE${NC}"
echo ""

# Étape 3: Vérifier le bucket S3/MinIO
echo -e "${BLUE}📋 Étape 3: Vérification du bucket MinIO${NC}"
echo "----------------------------------------------"

# Check if MinIO is running
if docker ps | grep -q "xpeditis-minio"; then
  echo -e "${GREEN}✅ MinIO container is running${NC}"
else
  echo -e "${RED}❌ MinIO container is NOT running${NC}"
  echo "Start it with: docker-compose up -d"
  exit 1
fi

# Check if bucket exists (via MinIO API)
echo "Checking if bucket 'xpeditis-documents' exists..."
BUCKET_CHECK=$(curl -s -I "http://localhost:9000/xpeditis-documents/" \
  -H "Authorization: AWS4-HMAC-SHA256 Credential=minioadmin/20231201/us-east-1/s3/aws4_request" 2>&1 | head -1)

if echo "$BUCKET_CHECK" | grep -q "200 OK"; then
  echo -e "${GREEN}✅ Bucket 'xpeditis-documents' exists${NC}"
elif echo "$BUCKET_CHECK" | grep -q "404"; then
  echo -e "${YELLOW}⚠️  Bucket 'xpeditis-documents' does NOT exist${NC}"
  echo "The backend will try to create it automatically, or it may fail."
else
  echo -e "${YELLOW}⚠️  Cannot verify bucket (MinIO might require auth)${NC}"
fi
echo ""

# Étape 4: Envoyer la requête de création de booking
echo -e "${BLUE}📋 Étape 4: Création du CSV booking${NC}"
echo "----------------------------------------------"

# Clear previous backend logs
echo "" > "$BACKEND_LOG.tail"
# Start tailing logs in background
tail -f "$BACKEND_LOG" > "$BACKEND_LOG.tail" &
TAIL_PID=$!

# Wait a second
sleep 1

echo "Sending POST request to /api/v1/csv-bookings..."
echo ""

# Send the booking request
BOOKING_RESPONSE=$(curl -s -w "\nHTTP_STATUS:%{http_code}" -X POST "${API_URL}/csv-bookings" \
  -H "Authorization: Bearer ${TOKEN}" \
  -F "carrierName=Test Maritime Express" \
  -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 booking via script" \
  -F "documents=@${TEST_FILE}" 2>&1)

# Extract HTTP status
HTTP_STATUS=$(echo "$BOOKING_RESPONSE" | grep "HTTP_STATUS" | cut -d':' -f2)
RESPONSE_BODY=$(echo "$BOOKING_RESPONSE" | sed '/HTTP_STATUS/d')

echo "HTTP Status: $HTTP_STATUS"
echo ""
echo "Response Body:"
echo "$RESPONSE_BODY" | head -50
echo ""

# Stop tailing
kill $TAIL_PID 2>/dev/null || true

# Wait a bit for logs to flush
sleep 2

# Étape 5: Analyser les logs backend
echo -e "${BLUE}📋 Étape 5: Analyse des logs backend${NC}"
echo "----------------------------------------------"

echo "Recent backend logs (CSV/Booking/Error related):"
tail -100 "$BACKEND_LOG" | grep -i "csv\|booking\|error\|email\|upload\|s3" | tail -30
echo ""

# Étape 6: Vérifier le résultat
echo "=========================================="
if [ "$HTTP_STATUS" = "201" ] || [ "$HTTP_STATUS" = "200" ]; then
  echo -e "${GREEN}✅ SUCCESS: Booking created successfully!${NC}"

  # Extract booking ID
  BOOKING_ID=$(echo "$RESPONSE_BODY" | grep -o '"id":"[^"]*"' | head -1 | cut -d'"' -f4)
  echo "Booking ID: $BOOKING_ID"
  echo ""
  echo "Check:"
  echo "1. Mailtrap inbox: https://mailtrap.io/inboxes"
  echo "2. Frontend bookings page: http://localhost:3000/dashboard/bookings"

elif [ "$HTTP_STATUS" = "400" ]; then
  echo -e "${RED}❌ FAILED: Bad Request (400)${NC}"
  echo "Possible issues:"
  echo "  - Missing required fields"
  echo "  - Invalid data format"
  echo "  - Document validation failed"

elif [ "$HTTP_STATUS" = "401" ]; then
  echo -e "${RED}❌ FAILED: Unauthorized (401)${NC}"
  echo "Possible issues:"
  echo "  - JWT token expired"
  echo "  - Invalid credentials"

elif [ "$HTTP_STATUS" = "500" ]; then
  echo -e "${RED}❌ FAILED: Internal Server Error (500)${NC}"
  echo "Possible issues:"
  echo "  - S3/MinIO connection failed"
  echo "  - Database error"
  echo "  - Email sending failed (check backend logs)"

else
  echo -e "${RED}❌ FAILED: Unknown error (HTTP $HTTP_STATUS)${NC}"
fi

echo "=========================================="
echo ""
echo "📄 Full backend logs available at: $BACKEND_LOG"
echo ""
