#!/bin/bash
# Test script to verify that the Gitea repository was created successfully

set -e

echo "=== Gitea Repository Creation Test ==="
echo

# Configuration - update these values as needed
GITEA_URL="https://gitea.bakery-ia.local"
GITEA_ADMIN_USER="bakery-admin"
REPO_NAME="bakery-ia"

# Check if Gitea admin password is set
if [ -z "$GITEA_ADMIN_PASSWORD" ]; then
    echo "Error: GITEA_ADMIN_PASSWORD environment variable is not set"
    echo "Please set it to the admin password you used during Gitea installation"
    exit 1
fi

echo "Testing Gitea accessibility..."
if ! curl -s -o /dev/null -w "%{http_code}" "$GITEA_URL" | grep -q "200"; then
    echo "❌ Error: Cannot access Gitea at $GITEA_URL"
    echo "Please ensure Gitea is running and accessible"
    exit 1
fi

echo "✅ Gitea is accessible"

echo "Testing repository existence..."
REPO_CHECK=$(curl -s -w "%{http_code}" -u "$GITEA_ADMIN_USER:$GITEA_ADMIN_PASSWORD" \
    "$GITEA_URL/api/v1/repos/$GITEA_ADMIN_USER/$REPO_NAME" | tail -1)

if [ "$REPO_CHECK" == "200" ]; then
    echo "✅ Repository '$REPO_NAME' exists"
    
    # Get repository details
    REPO_DETAILS=$(curl -s -u "$GITEA_ADMIN_USER:$GITEA_ADMIN_PASSWORD" \
        "$GITEA_URL/api/v1/repos/$GITEA_ADMIN_USER/$REPO_NAME")
    
    REPO_DESCRIPTION=$(echo "$REPO_DETAILS" | jq -r '.description')
    REPO_PRIVATE=$(echo "$REPO_DETAILS" | jq -r '.private')
    REPO_DEFAULT_BRANCH=$(echo "$REPO_DETAILS" | jq -r '.default_branch')
    
    echo "Repository Details:"
    echo "  - Name: $REPO_NAME"
    echo "  - Description: $REPO_DESCRIPTION"
    echo "  - Private: $REPO_PRIVATE"
    echo "  - Default Branch: $REPO_DEFAULT_BRANCH"
    echo "  - URL: $GITEA_URL/$GITEA_ADMIN_USER/$REPO_NAME"
    echo "  - Clone URL: $GITEA_URL/$GITEA_ADMIN_USER/$REPO_NAME.git"
    
    # Test if repository has issues enabled
    if echo "$REPO_DETAILS" | jq -e '.has_issues == true' > /dev/null; then
        echo "✅ Issues are enabled"
    else
        echo "❌ Issues are not enabled"
    fi
    
    # Test if repository has wiki enabled
    if echo "$REPO_DETAILS" | jq -e '.has_wiki == true' > /dev/null; then
        echo "✅ Wiki is enabled"
    else
        echo "❌ Wiki is not enabled"
    fi
    
    # Test if repository has pull requests enabled
    if echo "$REPO_DETAILS" | jq -e '.has_pull_requests == true' > /dev/null; then
        echo "✅ Pull requests are enabled"
    else
        echo "❌ Pull requests are not enabled"
    fi
    
    echo
    echo "✅ All tests passed! Repository is ready for use."
    
else
    echo "❌ Repository '$REPO_NAME' does not exist"
    echo "Expected HTTP 200, got: $REPO_CHECK"
    exit 1
fi

echo
echo "=== Test Complete ==="