#!/bin/bash

# Configuration
APP_URL="http://localhost"
EMAIL="test_script_$(date +%s)@example.com"
PASSWORD="password"
NAME="Test User"

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

# Statistics
TOTAL_TESTS=0
PASSED_TESTS=0
FAILED_TESTS=0

# Helper function for printing headers
print_header() {
    echo -e "\n${BLUE}=== $1 ===${NC}"
}

# Helper function for requests
# Usage: api_request METHOD ENDPOINT DATA [EXPECTED_STATUS] [DESCRIPTION]
api_request() {
    local method=$1
    local endpoint=$2
    local data=$3
    local expected_status=${4:-200}
    local description=$5

    ((TOTAL_TESTS++))
    
    echo -n "Test $((TOTAL_TESTS)): $description... "
    
    # Store response headers to get status code
    if [ -z "$TOKEN" ]; then
        response=$(curl -s -i -X "$method" "${APP_URL}${endpoint}" \
            -H "Content-Type: application/json" \
            -H "Accept: application/json" \
            -d "$data")
    else
        response=$(curl -s -i -X "$method" "${APP_URL}${endpoint}" \
            -H "Content-Type: application/json" \
            -H "Accept: application/json" \
            -H "Authorization: Bearer $TOKEN" \
            -d "$data")
    fi

    # Extract status code (handles HTTP/1.1 and HTTP/2)
    status_code=$(echo "$response" | grep -m 1 "HTTP/" | awk '{print $2}')
    body=$(echo "$response" | sed '1,/^\r$/d')

    if [ "$expected_status" == "2xx" ]; then
        if [[ "$status_code" =~ ^2 ]]; then
             echo -e "${GREEN}PASSED${NC} (${status_code})"
             ((PASSED_TESTS++))
             return 0
        else
             echo -e "${RED}FAILED${NC} (Expected 2xx, got $status_code)"
             echo -e "${YELLOW}Response:${NC} $body"
             ((FAILED_TESTS++))
             return 1
        fi
    elif [ "$status_code" -eq "$expected_status" ]; then
        echo -e "${GREEN}PASSED${NC} (${status_code})"
        ((PASSED_TESTS++))
        return 0
    else
        echo -e "${RED}FAILED${NC} (Expected $expected_status, got $status_code)"
        echo -e "${YELLOW}Response:${NC} $body"
        ((FAILED_TESTS++))
        return 1
    fi
}

echo -e "${BLUE}Starting API Endpoint Tests...${NC}"
echo "Target: $APP_URL"
echo "Time: $(date)"

# 1. Register
print_header "Authentication"
# We need to capture the body manually for token extraction while also using our helper checks if possible, 
# but simplify: do raw curl for registration to get token easily, then check status.
((TOTAL_TESTS++))
echo -n "Test $((TOTAL_TESTS)): Register User... "
response=$(curl -s -i -X POST "${APP_URL}/api/register" \
    -H "Content-Type: application/json" \
    -H "Accept: application/json" \
    -d "{\"name\":\"$NAME\",\"email\":\"$EMAIL\",\"password\":\"$PASSWORD\",\"password_confirmation\":\"$PASSWORD\"}")

status_code=$(echo "$response" | grep -m 1 "HTTP/" | awk '{print $2}')
body=$(echo "$response" | sed '1,/^\r$/d')

if [[ "$status_code" =~ ^2 ]]; then
    echo -e "${GREEN}PASSED${NC} ($status_code)"
    ((PASSED_TESTS++))
    TOKEN=$(echo $body | grep -o '"token":"[^"]*' | cut -d'"' -f4)

    # Manually verify user for testing purposes
    echo -n "Verifying User ($EMAIL)... "
    ./vendor/bin/sail artisan tinker --execute="App\Models\User::where('email', '$EMAIL')->first()->markEmailAsVerified();" > /dev/null 2>&1
    echo -e "${GREEN}VERIFIED${NC}"
else
    echo -e "${RED}FAILED${NC} ($status_code)"
    echo "$body"
    ((FAILED_TESTS++))
    exit 1
fi

# 2. Login
api_request "POST" "/api/login" "{\"email\":\"$EMAIL\",\"password\":\"$PASSWORD\"}" "2xx" "Login with credentials"

# 3. Get User
api_request "GET" "/api/user" "" "200" "Get authenticated user details"

# 4. Categories
print_header "Categories"
((TOTAL_TESTS++))
echo -n "Test $((TOTAL_TESTS)): Create Category... "
response=$(curl -s -i -X POST "${APP_URL}/api/categories" \
    -H "Content-Type: application/json" \
    -H "Accept: application/json" \
    -H "Authorization: Bearer $TOKEN" \
    -d "{\"name\":\"Script Category\",\"budget\":100}")

status_code=$(echo "$response" | grep -m 1 "HTTP/" | awk '{print $2}')
body=$(echo "$response" | sed '1,/^\r$/d')

if [[ "$status_code" =~ ^2 ]]; then
    echo -e "${GREEN}PASSED${NC} ($status_code)"
    ((PASSED_TESTS++))
    CAT_ID=$(echo $body | grep -o '"id":[^,]*' | head -1 | cut -d':' -f2 | tr -d ' }')
else
    echo -e "${RED}FAILED${NC} ($status_code)"
    echo "$body"
    ((FAILED_TESTS++))
fi

api_request "GET" "/api/categories" "" "200" "List categories"
api_request "PUT" "/api/categories/$CAT_ID" "{\"name\":\"Updated Script Category\",\"budget\":150}" "200" "Update category"

# 7. Transactions
print_header "Transactions"
((TOTAL_TESTS++))
echo -n "Test $((TOTAL_TESTS)): Create Transaction... "
GMAIL_ID="script_id_$(date +%s)"
response=$(curl -s -i -X POST "${APP_URL}/api/transactions" \
    -H "Content-Type: application/json" \
    -H "Accept: application/json" \
    -H "Authorization: Bearer $TOKEN" \
    -d "{\"amount\":50,\"type\":\"expense\",\"category_id\":$CAT_ID,\"gmail_id\":\"$GMAIL_ID\",\"description\":\"Script Test Transaction\"}")

status_code=$(echo "$response" | grep -m 1 "HTTP/" | awk '{print $2}')
body=$(echo "$response" | sed '1,/^\r$/d')

if [[ "$status_code" =~ ^2 ]]; then
    echo -e "${GREEN}PASSED${NC} ($status_code)"
    ((PASSED_TESTS++))
    TRANS_ID=$(echo $body | grep -o '"id":[^,]*' | head -1 | cut -d':' -f2 | tr -d ' }')
else
    echo -e "${RED}FAILED${NC} ($status_code)"
    echo "$body"
    ((FAILED_TESTS++))
fi

api_request "GET" "/api/transactions" "" "200" "List transactions"

if [[ "$OSTYPE" == "darwin"* ]]; then
    # MacOS
    DATE_FROM=$(date -v-1d +%Y-%m-%d)
    DATE_TO=$(date -v+1d +%Y-%m-%d)
else
    # Linux
    DATE_FROM=$(date -d "-1 day" +%Y-%m-%d)
    DATE_TO=$(date -d "+1 day" +%Y-%m-%d)
fi

api_request "GET" "/api/transactions/date-range?date_from=${DATE_FROM}&date_to=${DATE_TO}" "" "200" "Get transactions by date range"

api_request "PUT" "/api/transactions/$TRANS_ID" "{\"amount\":75,\"description\":\"Updated Transaction\"}" "200" "Update transaction"

# 11. Balance
print_header "Balance"
((TOTAL_TESTS++))
echo -n "Test $((TOTAL_TESTS)): Create Balance... "
response=$(curl -s -i -X POST "${APP_URL}/api/balance" \
    -H "Content-Type: application/json" \
    -H "Accept: application/json" \
    -H "Authorization: Bearer $TOKEN" \
    -d "{\"account_name\":\"Script Bank\",\"account_alias\":\"Main\",\"balance\":1000}")

status_code=$(echo "$response" | grep -m 1 "HTTP/" | awk '{print $2}')
body=$(echo "$response" | sed '1,/^\r$/d')

if [[ "$status_code" =~ ^2 ]]; then
    echo -e "${GREEN}PASSED${NC} ($status_code)"
    ((PASSED_TESTS++))
    BAL_ID=$(echo $body | grep -o '"id":[^,]*' | head -1 | cut -d':' -f2 | tr -d ' }')
else
    echo -e "${RED}FAILED${NC} ($status_code)"
    echo "$body"
    ((FAILED_TESTS++))
fi

api_request "GET" "/api/balance" "" "200" "Get balance"
api_request "PUT" "/api/balance/$BAL_ID" "{\"balance\":900}" "200" "Update balance"

# Cleanup
print_header "Cleanup"
api_request "DELETE" "/api/transactions/$TRANS_ID" "" "200" "Delete transaction"
api_request "DELETE" "/api/categories/$CAT_ID" "" "200" "Delete category"

# Summary
echo -e "\n${BLUE}=== Test Summary ===${NC}"
echo -e "Total Tests:  $TOTAL_TESTS"
echo -e "Passed:       ${GREEN}$PASSED_TESTS${NC}"
echo -e "Failed:       ${RED}$FAILED_TESTS${NC}"

if [ $FAILED_TESTS -eq 0 ]; then
    echo -e "\n${GREEN}✔ All tests passed successfully!${NC}"
    exit 0
else
    echo -e "\n${RED}✘ Some tests failed.${NC}"
    exit 1
fi
