#!/bin/bash
set -euo pipefail

# scripts/lab/test_auth.sh

API_URL="http://localhost:8080/api/v1"
EMAIL="test_auth_$(date +%s)@example.com"
PASSWORD="Password123!"

echo ">>> Testing Auth API..."
echo "Target: $API_URL"
echo "User: $EMAIL"

# 1. Register
echo -n "1. Registering... "
REGISTER_RES=$(curl -s -X POST "$API_URL/auth/register" \
  -H "Content-Type: application/json" \
  -d "{\"email\": \"$EMAIL\", \"password\": \"$PASSWORD\", \"username\": \"user_$(date +%s)\"}")

if echo "$REGISTER_RES" | grep -q "id"; then
    echo "OK"
else
    echo "FAIL"
    echo "Response: $REGISTER_RES"
    exit 1
fi

# 1.5 Manually Verify User (Bypass Email)
echo -n "1.5 Verifying User via DB... "
docker compose -f infra/docker-compose.lab.yml exec -T postgres psql -U veza -d veza_lab -c "UPDATE users SET is_verified=true WHERE email='$EMAIL';" > /dev/null 2>&1
echo "OK"

# 2. Login
echo -n "2. Logging in... "
LOGIN_RES=$(curl -s -X POST "$API_URL/auth/login" \
  -H "Content-Type: application/json" \
  -d "{\"email\": \"$EMAIL\", \"password\": \"$PASSWORD\"}")

if echo "$LOGIN_RES" | grep -q "access_token"; then
    echo "OK"
    TOKEN=$(echo "$LOGIN_RES" | grep -o '"access_token":"[^"]*' | cut -d'"' -f4)
    echo "Token received: ${TOKEN:0:10}..."
else
    echo "FAIL"
    echo "Response: $LOGIN_RES"
    exit 1
fi

# 3. Access Protected Route (Me)
echo -n "3. Accessing /auth/me... "
ME_RES=$(curl -s -X GET "$API_URL/auth/me" \
  -H "Authorization: Bearer $TOKEN")

if echo "$ME_RES" | grep -q "$EMAIL"; then
    echo "OK"
else
    echo "FAIL"
    echo "Response: $ME_RES"
    exit 1
fi

echo "✅ Auth API Verification Passed!"
