#!/bin/bash

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

BASE_URL="http://localhost:8000"
EMAIL="test$(date +%s)@basura.app"
PASSWORD="test123"
PHONE="4611234567"

echo -e "${YELLOW}=== BASURA APP TEST DEMO ===${NC}"
echo ""

# 1. Health check
echo -e "${YELLOW}1. Health Check${NC}"
HEALTH=$(curl -s $BASE_URL/health)
echo "Response: $HEALTH"
echo ""

# 2. Register
echo -e "${YELLOW}2. Register${NC}"
echo "Email: $EMAIL"
REGISTER=$(curl -s -X POST $BASE_URL/auth/register \
  -H "Content-Type: application/json" \
  -d "{
    \"email\": \"$EMAIL\",
    \"phone\": \"$PHONE\",
    \"password\": \"$PASSWORD\"
  }")
echo "Response: $REGISTER"
TOKEN=$(echo $REGISTER | grep -o '"access_token":"[^"]*"' | cut -d'"' -f4)
USER_ID=$(echo $REGISTER | grep -o '"user_id":"[^"]*"' | cut -d'"' -f4)

if [ -z "$TOKEN" ]; then
  echo -e "${RED}❌ Register failed - no token${NC}"
  exit 1
fi
echo -e "${GREEN}✓ Token: ${TOKEN:0:20}...${NC}"
echo -e "${GREEN}✓ User ID: $USER_ID${NC}"
echo ""

# 3. Create Address
echo -e "${YELLOW}3. Create Address${NC}"
ADDRESS=$(curl -s -X POST $BASE_URL/addresses/ \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $TOKEN" \
  -d '{
    "lat": 20.5285,
    "lng": -100.7980,
    "alias": "Casa",
    "address_text": "Celaya, Gto"
  }')
echo "Response: $ADDRESS"
ADDRESS_ID=$(echo $ADDRESS | grep -o '"id":[0-9]*' | cut -d':' -f2)

if [ -z "$ADDRESS_ID" ]; then
  echo -e "${RED}❌ Create address failed${NC}"
  exit 1
fi
echo -e "${GREEN}✓ Address ID: $ADDRESS_ID${NC}"
echo ""

# 4. Get Addresses
echo -e "${YELLOW}4. Get Addresses${NC}"
ADDRESSES=$(curl -s -X GET $BASE_URL/addresses/ \
  -H "Authorization: Bearer $TOKEN")
echo "Response: $ADDRESSES"
echo ""

# 5. Get ETA
echo -e "${YELLOW}5. Get ETA${NC}"
ETA=$(curl -s -X GET $BASE_URL/eta/$ADDRESS_ID \
  -H "Authorization: Bearer $TOKEN")
echo "Response: $ETA"
ROUTE_ID=$(echo $ETA | grep -o '"route_id":"[^"]*"' | cut -d'"' -f4)

if [ -z "$ROUTE_ID" ]; then
  echo -e "${RED}❌ ETA failed${NC}"
  exit 1
fi
echo -e "${GREEN}✓ Route ID: $ROUTE_ID${NC}"
echo ""

# 6. Recycling Guide
echo -e "${YELLOW}6. Get Recycling Guide${NC}"
GUIDE=$(curl -s -X GET $BASE_URL/recycling-guide)
CATEGORIES=$(echo $GUIDE | grep -o '"name":"[^"]*"' | wc -l)
echo "✓ Categories found: $CATEGORIES"
echo ""

echo -e "${GREEN}=== ALL TESTS PASSED ===${NC}"
echo ""
echo "Summary:"
echo "  User Email: $EMAIL"
echo "  User ID: $USER_ID"
echo "  Token: ${TOKEN:0:30}..."
echo "  Address ID: $ADDRESS_ID"
echo "  Route ID: $ROUTE_ID"
