#!/bin/bash
# Create GitLab repository using curl (alternative to Python script)

set -e

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

# Default values
GITLAB_URL="https://gitlab.com"
PROJECT_NAME="pg-api"
VISIBILITY="public"
DESCRIPTION="High-performance PostgreSQL REST API driver built with Rust"

# Check for required token
if [ -z "$GITLAB_TOKEN" ]; then
    echo -e "${RED}Error: GITLAB_TOKEN environment variable is required${NC}"
    echo "Usage: GITLAB_TOKEN=your_token ./create_gitlab_repo.sh"
    exit 1
fi

# Function to make GitLab API calls
gitlab_api() {
    local endpoint=$1
    local method=${2:-GET}
    local data=$3
    
    if [ -z "$data" ]; then
        curl -s -X "$method" \
            -H "PRIVATE-TOKEN: $GITLAB_TOKEN" \
            -H "Content-Type: application/json" \
            "${GITLAB_URL}/api/v4${endpoint}"
    else
        curl -s -X "$method" \
            -H "PRIVATE-TOKEN: $GITLAB_TOKEN" \
            -H "Content-Type: application/json" \
            -d "$data" \
            "${GITLAB_URL}/api/v4${endpoint}"
    fi
}

echo "🔍 Getting user information..."
USER_INFO=$(gitlab_api "/user")
USERNAME=$(echo "$USER_INFO" | grep -o '"username":"[^"]*' | cut -d'"' -f4)

if [ -z "$USERNAME" ]; then
    echo -e "${RED}Failed to authenticate. Check your GITLAB_TOKEN${NC}"
    exit 1
fi

echo -e "${GREEN}✅ Authenticated as: $USERNAME${NC}"

# Create the repository
echo "📦 Creating repository '$PROJECT_NAME'..."

CREATE_DATA=$(cat <<EOF
{
    "name": "$PROJECT_NAME",
    "description": "$DESCRIPTION",
    "visibility": "$VISIBILITY",
    "issues_enabled": true,
    "merge_requests_enabled": true,
    "wiki_enabled": true,
    "container_registry_enabled": true,
    "packages_enabled": true,
    "auto_devops_enabled": false,
    "topics": "postgresql,rust,api,rest-api,database,driver,axum,tokio"
}
EOF
)

RESPONSE=$(gitlab_api "/projects" "POST" "$CREATE_DATA")

# Check if creation was successful
if echo "$RESPONSE" | grep -q '"id"'; then
    PROJECT_ID=$(echo "$RESPONSE" | grep -o '"id":[0-9]*' | head -1 | cut -d':' -f2)
    WEB_URL=$(echo "$RESPONSE" | grep -o '"web_url":"[^"]*' | cut -d'"' -f4)
    SSH_URL=$(echo "$RESPONSE" | grep -o '"ssh_url_to_repo":"[^"]*' | cut -d'"' -f4)
    
    echo -e "${GREEN}✅ Repository created successfully!${NC}"
    echo "📍 Web URL: $WEB_URL"
    echo "📍 SSH URL: $SSH_URL"
    
    # Initialize git if needed
    if [ ! -d .git ]; then
        echo "🔧 Initializing git repository..."
        git init
        git add .
        git commit -m "Initial commit: pg-api PostgreSQL REST API driver"
    fi
    
    # Add remote and push
    echo "📤 Adding GitLab remote..."
    git remote remove origin 2>/dev/null || true
    git remote add origin "$SSH_URL"
    
    echo "📤 Pushing to GitLab..."
    git branch -M main
    git push -u origin main
    
    echo -e "${GREEN}🎉 Success! Your repository is ready at:${NC}"
    echo "$WEB_URL"
    
elif echo "$RESPONSE" | grep -q "has already been taken"; then
    echo -e "${YELLOW}ℹ️  Repository '$PROJECT_NAME' already exists${NC}"
    echo "📍 URL: ${GITLAB_URL}/${USERNAME}/${PROJECT_NAME}"
    
    # Add remote if not exists
    if ! git remote | grep -q origin; then
        git remote add origin "git@gitlab.com:${USERNAME}/${PROJECT_NAME}.git"
    fi
    
    echo -e "${YELLOW}To push your changes:${NC}"
    echo "  git push -u origin main"
else
    echo -e "${RED}❌ Failed to create repository${NC}"
    echo "Response: $RESPONSE"
    exit 1
fi