#!/bin/bash

set -e

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

echo -e "${BLUE}🧪 Testing release existence check...${NC}"

# Get current version
VERSION=$(node -p "require('./package.json').version")
echo -e "${YELLOW}Current version: ${VERSION}${NC}"

# Check if we're in a git repository
if [ ! -d ".git" ]; then
    echo -e "${RED}❌ Not in a git repository${NC}"
    exit 1
fi

# Get repository info
REPO_URL=$(git remote get-url origin)
if [[ $REPO_URL == *"github.com"* ]]; then
    # Extract owner/repo from git URL
    if [[ $REPO_URL == *"git@github.com:"* ]]; then
        REPO_PATH=$(echo $REPO_URL | sed 's/git@github.com://' | sed 's/\.git$//')
    elif [[ $REPO_URL == *"https://github.com/"* ]]; then
        REPO_PATH=$(echo $REPO_URL | sed 's/https:\/\/github.com\///' | sed 's/\.git$//')
    else
        echo -e "${RED}❌ Could not parse GitHub repository URL${NC}"
        exit 1
    fi
    
    echo -e "${YELLOW}Repository: ${REPO_PATH}${NC}"
    
    # Check if release exists
    echo -e "${YELLOW}🔍 Checking if release v${VERSION} exists...${NC}"
    RELEASE_EXISTS=$(curl -s -o /dev/null -w "%{http_code}" \
        "https://api.github.com/repos/${REPO_PATH}/releases/tags/v${VERSION}")
    
    if [ "$RELEASE_EXISTS" = "200" ]; then
        echo -e "${GREEN}✅ Release v${VERSION} already exists${NC}"
        
        # Get release details
        RELEASE_INFO=$(curl -s "https://api.github.com/repos/${REPO_PATH}/releases/tags/v${VERSION}")
        RELEASE_ID=$(echo "$RELEASE_INFO" | jq -r '.id')
        RELEASE_NAME=$(echo "$RELEASE_INFO" | jq -r '.name')
        
        echo -e "${BLUE}Release ID: ${RELEASE_ID}${NC}"
        echo -e "${BLUE}Release Name: ${RELEASE_NAME}${NC}"
    else
        echo -e "${YELLOW}ℹ️ Release v${VERSION} does not exist (HTTP ${RELEASE_EXISTS})${NC}"
    fi
else
    echo -e "${YELLOW}⚠️ Not a GitHub repository, skipping release check${NC}"
fi

echo -e "${GREEN}✅ Release existence check completed!${NC}" 