#!/bin/bash

# Blog API End-to-End Test Script
# Tests all Blog API endpoints as specified in Linear task 09-152

set -e  # Exit on error

# Configuration
API_BASE="http://localhost:8000/api"
ADMIN_API="${API_BASE}/admin"
PUBLIC_API="${API_BASE}/blogs"

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

# Test results
TESTS_PASSED=0
TESTS_FAILED=0

# Function to print test headers
print_test() {
    echo -e "\n${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${BLUE}TEST: $1${NC}"
    echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
}

# Function to print success
print_success() {
    echo -e "${GREEN}✅ $1${NC}"
    ((TESTS_PASSED++))
}

# Function to print failure
print_failure() {
    echo -e "${RED}❌ $1${NC}"
    ((TESTS_FAILED++))
}

# Function to print info
print_info() {
    echo -e "${YELLOW}ℹ️  $1${NC}"
}

# Function to check if jq is installed
check_dependencies() {
    if ! command -v jq &> /dev/null; then
        print_failure "jq is not installed. Please install it: brew install jq"
        exit 1
    fi
}

# Function to get admin JWT token
get_admin_token() {
    print_info "Authenticating as admin..."

    # Login as admin (adjust credentials as needed)
    local response=$(curl -s -X POST "${API_BASE}/admin/login" \
        -H "Content-Type: application/json" \
        -d '{
            "email": "admin@showprima.com",
            "password": "admin123"
        }')

    # Extract token
    local token=$(echo $response | jq -r '.data.token // .token // empty')

    if [ -z "$token" ]; then
        print_failure "Failed to get admin token. Please check credentials."
        print_info "Response: $response"
        exit 1
    fi

    print_success "Admin authenticated successfully"
    echo "$token"
}

# Function to create test image
create_test_image() {
    local filename="$1"

    # Create a simple 100x100 PNG test image using ImageMagick or Python
    if command -v convert &> /dev/null; then
        convert -size 100x100 xc:blue "$filename"
    elif command -v python3 &> /dev/null; then
        python3 -c "
from PIL import Image
img = Image.new('RGB', (100, 100), color='blue')
img.save('$filename')
"
    else
        # Fallback: create a minimal valid PNG
        printf '\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x02\x00\x00\x00\x90wS\xde' > "$filename"
        printf '\x00\x00\x00\x0cIDATx\x9cc\x00\x01\x00\x00\x05\x00\x01\r\n-\xb4\x00\x00\x00\x00IEND\xaeB`\x82' >> "$filename"
    fi
}

# Main test execution
main() {
    echo -e "${BLUE}"
    echo "╔══════════════════════════════════════════════════════════╗"
    echo "║         Blog API End-to-End Test Suite                  ║"
    echo "║         Linear Task: 09-152                              ║"
    echo "╚══════════════════════════════════════════════════════════╝"
    echo -e "${NC}"

    check_dependencies

    # Get admin token
    ADMIN_TOKEN=$(get_admin_token)
    AUTH_HEADER="Authorization: Bearer ${ADMIN_TOKEN}"

    # Variables for storing test data
    BLOG_ID=""
    BLOG_SLUG=""
    INITIAL_VIEWS=0

    # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
    # TEST 1: Get categories
    # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
    print_test "1. GET /api/admin/blog-categories"

    response=$(curl -s -X GET "${ADMIN_API}/blog-categories" \
        -H "$AUTH_HEADER")

    if echo "$response" | jq -e '.success == true' > /dev/null 2>&1; then
        CATEGORY_ID=$(echo "$response" | jq -r '.data.data[0].id // .data[0].id // 1')
        print_success "Categories retrieved successfully"
        print_info "Using category_id: $CATEGORY_ID"
    else
        print_failure "Failed to get categories"
        print_info "Response: $response"
        exit 1
    fi

    # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
    # TEST 2: Create blog with image
    # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
    print_test "2. POST /api/admin/blogs (with image)"

    # Create test image
    TEST_IMAGE="/tmp/test_blog_image.png"
    create_test_image "$TEST_IMAGE"
    print_info "Test image created: $TEST_IMAGE"

    response=$(curl -s -X POST "${ADMIN_API}/blogs" \
        -H "$AUTH_HEADER" \
        -F "category_id=$CATEGORY_ID" \
        -F "title=Test Blog Article $(date +%s)" \
        -F "description=This is a comprehensive test blog article created via API. It includes all required fields and an image upload." \
        -F "image=@${TEST_IMAGE}" \
        -F "is_published=1" \
        -F "show_on_homepage=1" \
        -F "status=1")

    if echo "$response" | jq -e '.success == true' > /dev/null 2>&1; then
        BLOG_ID=$(echo "$response" | jq -r '.data.id')
        BLOG_SLUG=$(echo "$response" | jq -r '.data.slug')
        IMAGE_PATH=$(echo "$response" | jq -r '.data.image')

        print_success "Blog created successfully"
        print_info "Blog ID: $BLOG_ID"
        print_info "Blog Slug: $BLOG_SLUG"
        print_info "Image Path: $IMAGE_PATH"

        # Verify slug was auto-generated
        if [ -n "$BLOG_SLUG" ] && [ "$BLOG_SLUG" != "null" ]; then
            print_success "Slug auto-generated from title"
        else
            print_failure "Slug was not auto-generated"
        fi

        # Verify image path
        if [[ "$IMAGE_PATH" == blogs/* ]]; then
            print_success "Image stored in correct path: storage/app/public/$IMAGE_PATH"
        else
            print_failure "Image path incorrect: $IMAGE_PATH"
        fi
    else
        print_failure "Failed to create blog"
        print_info "Response: $response"
        exit 1
    fi

    # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
    # TEST 3: List blogs
    # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
    print_test "3. GET /api/admin/blogs"

    response=$(curl -s -X GET "${ADMIN_API}/blogs" \
        -H "$AUTH_HEADER")

    if echo "$response" | jq -e '.success == true' > /dev/null 2>&1; then
        BLOG_COUNT=$(echo "$response" | jq -r '.data.data | length')
        print_success "Blogs listed successfully"
        print_info "Total blogs: $BLOG_COUNT"

        # Verify our created blog is in the list
        FOUND=$(echo "$response" | jq -r ".data.data[] | select(.id == $BLOG_ID) | .id")
        if [ "$FOUND" == "$BLOG_ID" ]; then
            print_success "Created blog found in list"
        else
            print_failure "Created blog not found in list"
        fi
    else
        print_failure "Failed to list blogs"
        print_info "Response: $response"
    fi

    # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
    # TEST 4: Update blog
    # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
    print_test "4. POST /api/admin/blogs/$BLOG_ID (update)"

    # Create a new test image for update
    NEW_TEST_IMAGE="/tmp/test_blog_image_updated.png"
    create_test_image "$NEW_TEST_IMAGE"

    response=$(curl -s -X POST "${ADMIN_API}/blogs/${BLOG_ID}" \
        -H "$AUTH_HEADER" \
        -F "title=Updated Test Blog Article" \
        -F "description=This blog has been updated with new content and a new image." \
        -F "image=@${NEW_TEST_IMAGE}")

    if echo "$response" | jq -e '.success == true' > /dev/null 2>&1; then
        NEW_IMAGE_PATH=$(echo "$response" | jq -r '.data.image')
        print_success "Blog updated successfully"
        print_info "New image path: $NEW_IMAGE_PATH"

        # Verify image was replaced
        if [ "$NEW_IMAGE_PATH" != "$IMAGE_PATH" ]; then
            print_success "Old image replaced with new image"
            print_info "Note: Old image should be deleted from storage"
        else
            print_failure "Image was not replaced"
        fi

        IMAGE_PATH="$NEW_IMAGE_PATH"
    else
        print_failure "Failed to update blog"
        print_info "Response: $response"
    fi

    # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
    # TEST 5: Toggle status
    # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
    print_test "5. POST /api/admin/blogs/$BLOG_ID/toggle-status"

    response=$(curl -s -X POST "${ADMIN_API}/blogs/${BLOG_ID}/toggle-status" \
        -H "$AUTH_HEADER")

    if echo "$response" | jq -e '.success == true' > /dev/null 2>&1; then
        NEW_STATUS=$(echo "$response" | jq -r '.data.status')
        print_success "Blog status toggled successfully"
        print_info "New status: $NEW_STATUS"

        # Toggle back
        response=$(curl -s -X POST "${ADMIN_API}/blogs/${BLOG_ID}/toggle-status" \
            -H "$AUTH_HEADER")

        if echo "$response" | jq -e '.success == true' > /dev/null 2>&1; then
            RESTORED_STATUS=$(echo "$response" | jq -r '.data.status')
            print_success "Blog status toggled back successfully"
            print_info "Restored status: $RESTORED_STATUS"
        else
            print_failure "Failed to toggle status back"
        fi
    else
        print_failure "Failed to toggle blog status"
        print_info "Response: $response"
    fi

    # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
    # TEST 6: Public view (increment views)
    # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
    print_test "6. GET /api/blogs/$BLOG_SLUG (public view)"

    response=$(curl -s -X GET "${PUBLIC_API}/${BLOG_SLUG}")

    if echo "$response" | jq -e '.success == true' > /dev/null 2>&1; then
        BLOG_VIEWS=$(echo "$response" | jq -r '.data.blog_views')
        print_success "Blog retrieved via public endpoint"
        print_info "Current views: $BLOG_VIEWS"

        # Access again to test view increment
        sleep 1
        response=$(curl -s -X GET "${PUBLIC_API}/${BLOG_SLUG}")
        NEW_VIEWS=$(echo "$response" | jq -r '.data.blog_views')

        if [ "$NEW_VIEWS" -gt "$BLOG_VIEWS" ]; then
            print_success "Blog views incremented on public access"
            print_info "Views increased from $BLOG_VIEWS to $NEW_VIEWS"
        else
            print_failure "Blog views did not increment"
        fi
    else
        print_failure "Failed to retrieve blog via public endpoint"
        print_info "Response: $response"
    fi

    # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
    # TEST 7: Verify image accessibility
    # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
    print_test "Additional: Verify image accessibility"

    # Extract filename from image path
    IMAGE_FILENAME=$(basename "$IMAGE_PATH")
    IMAGE_URL="http://localhost:8000/storage/blogs/${IMAGE_FILENAME}"

    http_code=$(curl -s -o /dev/null -w "%{http_code}" "$IMAGE_URL")

    if [ "$http_code" == "200" ]; then
        print_success "Image accessible via /storage/blogs/${IMAGE_FILENAME}"
        print_info "URL: $IMAGE_URL"
    else
        print_failure "Image not accessible (HTTP $http_code)"
        print_info "URL: $IMAGE_URL"
        print_info "Make sure 'php artisan storage:link' has been run"
    fi

    # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
    # TEST 8: Delete blog
    # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
    print_test "7. DELETE /api/admin/blogs/$BLOG_ID"

    response=$(curl -s -X DELETE "${ADMIN_API}/blogs/${BLOG_ID}" \
        -H "$AUTH_HEADER")

    if echo "$response" | jq -e '.success == true' > /dev/null 2>&1; then
        print_success "Blog deleted successfully"

        # Verify blog no longer exists
        response=$(curl -s -X GET "${ADMIN_API}/blogs/${BLOG_ID}" \
            -H "$AUTH_HEADER")

        if echo "$response" | jq -e '.success == false' > /dev/null 2>&1; then
            print_success "Confirmed blog no longer exists"
        else
            print_failure "Blog still exists after deletion"
        fi

        # Verify image was deleted
        sleep 1
        http_code=$(curl -s -o /dev/null -w "%{http_code}" "$IMAGE_URL")
        if [ "$http_code" == "404" ]; then
            print_success "Image file deleted from storage"
        else
            print_failure "Image file still exists (HTTP $http_code)"
        fi
    else
        print_failure "Failed to delete blog"
        print_info "Response: $response"
    fi

    # Cleanup
    rm -f "$TEST_IMAGE" "$NEW_TEST_IMAGE"

    # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
    # Test Summary
    # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
    echo -e "\n${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${BLUE}TEST SUMMARY${NC}"
    echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${GREEN}Passed: $TESTS_PASSED${NC}"
    echo -e "${RED}Failed: $TESTS_FAILED${NC}"

    if [ $TESTS_FAILED -eq 0 ]; then
        echo -e "\n${GREEN}🎉 All tests passed! Blog API is working correctly.${NC}\n"
        exit 0
    else
        echo -e "\n${RED}⚠️  Some tests failed. Please review the output above.${NC}\n"
        exit 1
    fi
}

# Run tests
main
