#!/bin/bash

# Cartec API Test Runner
# Simple bash-based tests using curl

API_URL="http://localhost:3000"
PASSED=0
FAILED=0

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

echo -e "${BLUE}========================================"
echo "  Cartec API Test Suite (Bash)"
echo "========================================${NC}"
echo "API URL: $API_URL"
echo ""

# Test 1: Health Check
echo -e "${BLUE}Test 1: Health Check${NC}"
RESPONSE=$(curl -s -w "\n%{http_code}" "$API_URL/api/health")
HTTP_CODE=$(echo "$RESPONSE" | tail -n1)
BODY=$(echo "$RESPONSE" | sed '$d')

if [ "$HTTP_CODE" = "200" ]; then
    echo -e "${GREEN}✓ Health check passed (HTTP 200)${NC}"
    ((PASSED++))
else
    echo -e "${RED}✗ Health check failed (HTTP $HTTP_CODE)${NC}"
    ((FAILED++))
fi
echo ""

# Test 2: Invalid GPS Provider
echo -e "${BLUE}Test 2: Invalid GPS Provider${NC}"
RESPONSE=$(curl -s -w "\n%{http_code}" -X POST "$API_URL/api/ot/create" \
  -H "Content-Type: application/json" \
  -d '{
    "cliente": {"rut": "12345678-9", "nombre": "Test", "direccion": "Test", "comuna": "Test", "telefono": "123", "email": "test@test.cl"},
    "tecnico": {"rut": "98765432-1"},
    "servicio": {"presGPS": "invalid_gps", "tiposerv": "instalacion_gps", "taller_install": "cartec"},
    "vehiculos": [{"patente": "TEST", "marca": "Test", "modelo": "Test", "color": "Test", "anio": 2020}]
  }')
HTTP_CODE=$(echo "$RESPONSE" | tail -n1)

if [ "$HTTP_CODE" = "400" ]; then
    echo -e "${GREEN}✓ Invalid GPS provider rejected (HTTP 400)${NC}"
    ((PASSED++))
else
    echo -e "${RED}✗ Invalid GPS provider test failed (HTTP $HTTP_CODE)${NC}"
    ((FAILED++))
fi
echo ""

# Test 3: Valid GPS Providers
echo -e "${BLUE}Test 3: Valid GPS Providers${NC}"
GPS_PROVIDERS=("gpsimple" "entel" "tattersall" "cemin" "carflex")

for PROVIDER in "${GPS_PROVIDERS[@]}"; do
    RESPONSE=$(curl -s -w "\n%{http_code}" -X POST "$API_URL/api/ot/create" \
      -H "Content-Type: application/json" \
      -d "{
        \"cliente\": {\"rut\": \"12345678-9\", \"nombre\": \"Test\", \"direccion\": \"Test\", \"comuna\": \"Test\", \"telefono\": \"123\", \"email\": \"test@test.cl\"},
        \"tecnico\": {\"rut\": \"98765432-1\"},
        \"servicio\": {\"presGPS\": \"$PROVIDER\", \"tiposerv\": \"instalacion_gps\", \"taller_install\": \"cartec\"},
        \"vehiculos\": [{\"patente\": \"TEST\", \"marca\": \"Test\", \"modelo\": \"Test\", \"color\": \"Test\", \"anio\": 2020}]
      }")
    HTTP_CODE=$(echo "$RESPONSE" | tail -n1)
    BODY=$(echo "$RESPONSE" | sed '$d')
    
    # Check if validation passed (not 400 with GPS provider error)
    if echo "$BODY" | grep -q "servicio.presGPS"; then
        echo -e "${RED}✗ GPS provider '$PROVIDER' rejected${NC}"
        ((FAILED++))
    else
        echo -e "${GREEN}✓ GPS provider '$PROVIDER' accepted${NC}"
        ((PASSED++))
    fi
done
echo ""

# Test 4: Invalid Email
echo -e "${BLUE}Test 4: Invalid Email${NC}"
RESPONSE=$(curl -s -w "\n%{http_code}" -X POST "$API_URL/api/ot/create" \
  -H "Content-Type: application/json" \
  -d '{
    "cliente": {"rut": "12345678-9", "nombre": "Test", "direccion": "Test", "comuna": "Test", "telefono": "123", "email": "invalid-email"},
    "tecnico": {"rut": "98765432-1"},
    "servicio": {"presGPS": "gpsimple", "tiposerv": "instalacion_gps", "taller_install": "cartec"},
    "vehiculos": [{"patente": "TEST", "marca": "Test", "modelo": "Test", "color": "Test", "anio": 2020}]
  }')
HTTP_CODE=$(echo "$RESPONSE" | tail -n1)

if [ "$HTTP_CODE" = "400" ]; then
    echo -e "${GREEN}✓ Invalid email rejected (HTTP 400)${NC}"
    ((PASSED++))
else
    echo -e "${RED}✗ Invalid email test failed (HTTP $HTTP_CODE)${NC}"
    ((FAILED++))
fi
echo ""

# Test 5: Missing Vehicles
echo -e "${BLUE}Test 5: Missing Vehicles${NC}"
RESPONSE=$(curl -s -w "\n%{http_code}" -X POST "$API_URL/api/ot/create" \
  -H "Content-Type: application/json" \
  -d '{
    "cliente": {"rut": "12345678-9", "nombre": "Test", "direccion": "Test", "comuna": "Test", "telefono": "123", "email": "test@test.cl"},
    "tecnico": {"rut": "98765432-1"},
    "servicio": {"presGPS": "gpsimple", "tiposerv": "instalacion_gps", "taller_install": "cartec"},
    "vehiculos": []
  }')
HTTP_CODE=$(echo "$RESPONSE" | tail -n1)

if [ "$HTTP_CODE" = "400" ]; then
    echo -e "${GREEN}✓ Missing vehicles rejected (HTTP 400)${NC}"
    ((PASSED++))
else
    echo -e "${RED}✗ Missing vehicles test failed (HTTP $HTTP_CODE)${NC}"
    ((FAILED++))
fi
echo ""

# Test 6: Valid OT Creation (may fail if DB not configured)
echo -e "${BLUE}Test 6: Valid OT Creation${NC}"
echo -e "${YELLOW}Note: This test may fail if database is not properly configured${NC}"
RESPONSE=$(curl -s -w "\n%{http_code}" -X POST "$API_URL/api/ot/create" \
  -H "Content-Type: application/json" \
  -d '{
    "cliente": {
      "rut": "12345678-9",
      "nombre": "Test Cliente",
      "direccion": "Av. Test 123",
      "comuna": "Santiago",
      "telefono": "+56912345678",
      "email": "test@example.com"
    },
    "tecnico": {
      "rut": "98765432-1"
    },
    "servicio": {
      "presGPS": "gpsimple",
      "tiposerv": "instalacion_gps",
      "taller_install": "cartec"
    },
    "vehiculos": [
      {
        "patente": "TEST01",
        "marca": "Toyota",
        "modelo": "Corolla",
        "color": "Blanco",
        "anio": 2020
      }
    ]
  }')
HTTP_CODE=$(echo "$RESPONSE" | tail -n1)
BODY=$(echo "$RESPONSE" | sed '$d')

if [ "$HTTP_CODE" = "201" ]; then
    echo -e "${GREEN}✓ OT created successfully (HTTP 201)${NC}"
    if command -v python3 &> /dev/null; then
        echo "$BODY" | python3 -m json.tool
    else
        echo "$BODY"
    fi
    ((PASSED++))
elif [ "$HTTP_CODE" = "404" ]; then
    echo -e "${YELLOW}⚠ Technician not found (HTTP 404) - expected if test data not in DB${NC}"
    echo "  This is not counted as a failure"
elif [ "$HTTP_CODE" = "500" ]; then
    echo -e "${YELLOW}⚠ Server error (HTTP 500) - check database configuration${NC}"
    echo "  Response: $BODY"
    echo "  This is not counted as a failure"
else
    echo -e "${RED}✗ OT creation test failed (HTTP $HTTP_CODE)${NC}"
    echo "  Response: $BODY"
    ((FAILED++))
fi
echo ""

# Results
echo -e "${BLUE}========================================"
echo "  Test Results"
echo "========================================${NC}"
echo -e "${GREEN}Passed: $PASSED${NC}"
echo -e "${RED}Failed: $FAILED${NC}"
echo "Total: $((PASSED + FAILED))"
echo ""

if [ $FAILED -eq 0 ]; then
    echo -e "${GREEN}All tests passed! ✓${NC}"
    exit 0
else
    echo -e "${RED}Some tests failed ✗${NC}"
    exit 1
fi

