#!/bin/bash
# Test script to reproduce registration bug
# This is the RED test that should fail initially

set -euo pipefail

# Source test environment
cd "$(dirname "${BASH_SOURCE[0]}")/.."
source .env
source http/http_assert.sh

echo "Testing registration bug reproduction..."

# Test 1: Valid registration should return 201
TEST_EMAIL="user+bug$(date +%s)@lab.veza"
TEST_PASSWORD="V3za!test-$(date +%s)"

echo "Testing valid registration..."
response=$(curl -skw '\n%{http_code}\n' \
  -H 'Content-Type: application/json' \
  -d "{\"username\":\"testuser\",\"email\":\"$TEST_EMAIL\",\"password\":\"$TEST_PASSWORD\"}" \
  "$API_ORIGIN/api/auth/register")

body=$(echo "$response" | sed '$d')
code=$(echo "$response" | tail -1)

echo "Response code: $code"
echo "Response body: $body"

# This should return 201 but might return 4xx/5xx
if [ "$code" -ne 201 ]; then
    echo "❌ BUG CONFIRMED: Registration returns $code instead of 201"
    echo "Body: $body"
    exit 1
else
    echo "✅ Registration returned 201 as expected"
fi

# Test 2: Duplicate registration should return 409
echo -e "\nTesting duplicate registration..."
response=$(curl -skw '\n%{http_code}\n' \
  -H 'Content-Type: application/json' \
  -d "{\"username\":\"testuser\",\"email\":\"$TEST_EMAIL\",\"password\":\"$TEST_PASSWORD\"}" \
  "$API_ORIGIN/api/auth/register")

code=$(echo "$response" | tail -1)
if [ "$code" -ne 409 ]; then
    echo "❌ Duplicate registration returns $code instead of 409"
    exit 1
else
    echo "✅ Duplicate registration correctly returns 409"
fi

echo -e "\n✅ All registration tests passed!"