#!/bin/bash

# Quick Notion API Key Test
# Usage: ./scripts/quick-notion-test.sh [api-key]

set -e

echo "🔧 Notion API Key Quick Test"
echo "=============================="

# Get API key from argument or .env file
if [ -n "$1" ]; then
    API_KEY="$1"
    echo "Using API key from command line: ${API_KEY:0:10}..."
else
    # Try to read from .env file
    if [ -f ".env" ]; then
        API_KEY=$(grep 'NOTION_API_KEY=' .env | cut -d'"' -f2)
        if [ -n "$API_KEY" ]; then
            echo "Using API key from .env file: ${API_KEY:0:10}..."
        else
            echo "❌ No API key found in .env file"
            echo ""
            echo "Usage:"
            echo "  ./scripts/quick-notion-test.sh ntn_your_api_key_here"
            echo "  OR set NOTION_API_KEY in .env file first"
            exit 1
        fi
    else
        echo "❌ .env file not found"
        exit 1
    fi
fi

# Test the API key
echo ""
echo "Testing API key..."
RESPONSE=$(curl -s -w "\n%{http_code}" \
  -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  -H "Notion-Version: 2022-06-28" \
  https://api.notion.com/v1/users/me)

HTTP_CODE=$(echo "$RESPONSE" | tail -n1)
RESPONSE_BODY=$(echo "$RESPONSE" | head -n -1)

if [ "$HTTP_CODE" = "200" ]; then
    echo "✅ API key is VALID"
    USER_NAME=$(echo "$RESPONSE_BODY" | grep -o '"name":"[^"]*"' | cut -d'"' -f4 || echo "Unknown")
    echo "   User: $USER_NAME"
    
    # Test one database as sample
    echo ""
    echo "Testing Business State database access..."
    DB_ID="2f563e0c-a7d5-8116-89bb-de6bdde99011"
    DB_RESPONSE=$(curl -s -w "\n%{http_code}" \
      -X POST \
      -H "Authorization: Bearer $API_KEY" \
      -H "Content-Type: application/json" \
      -H "Notion-Version: 2022-06-28" \
      -d '{"page_size": 1}' \
      https://api.notion.com/v1/databases/$DB_ID/query)
    
    DB_HTTP_CODE=$(echo "$DB_RESPONSE" | tail -n1)
    if [ "$DB_HTTP_CODE" = "200" ]; then
        echo "✅ Database accessible"
        ENTRY_COUNT=$(echo "$DB_RESPONSE" | head -n -1 | grep -o '"results":\[.*\]' | jq '.results | length' 2>/dev/null || echo "Unknown")
        echo "   Entries: $ENTRY_COUNT"
    elif [ "$DB_HTTP_CODE" = "404" ]; then
        echo "❌ Database not found (404)"
        echo "   Check if database is shared with integration"
    elif [ "$DB_HTTP_CODE" = "403" ]; then
        echo "❌ Permission denied (403)"
        echo "   Integration needs access to this database"
    else
        echo "⚠️  Database test returned: $DB_HTTP_CODE"
    fi
    
    echo ""
    echo "🎉 API key is working!"
    echo ""
    echo "Next steps:"
    echo "1. If testing a new key, update .env file:"
    echo "   NOTION_API_KEY=\"$API_KEY\""
    echo "2. Run full test: node scripts/test-notion-key.js"
    echo "3. Restart any services using Notion API"
    
elif [ "$HTTP_CODE" = "401" ]; then
    echo "❌ API key is INVALID (401 Unauthorized)"
    ERROR_MSG=$(echo "$RESPONSE_BODY" | grep -o '"message":"[^"]*"' | cut -d'"' -f4 || echo "Unknown error")
    echo "   Error: $ERROR_MSG"
    echo ""
    echo "Action required:"
    echo "1. Get new API key from https://www.notion.so/my-integrations"
    echo "2. Update .env file with new key"
    echo "3. Run this test again"
    exit 1
else
    echo "⚠️  Unexpected response: HTTP $HTTP_CODE"
    echo "   Response: $RESPONSE_BODY"
    exit 1
fi