#!/bin/bash

###############################################################################
# Critical API Endpoints Test Script
# Tests essential endpoints to verify no dead code removal broke functionality
###############################################################################

set -e

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

# Configuration
API_URL="${API_URL:-http://localhost:8001/api}"
ADMIN_EMAIL="${ADMIN_EMAIL:-admin@showprima.com}"
ADMIN_PASSWORD="${ADMIN_PASSWORD:-password}"

# Counters
PASSED=0
FAILED=0
TOTAL=0

# Helper function to test endpoint
test_endpoint() {
    local name="$1"
    local method="$2"
    local endpoint="$3"
    local headers="$4"
    local data="$5"
    local expected_text="$6"

    TOTAL=$((TOTAL + 1))
    echo -n "Testing: $name... "

    if [ "$method" = "GET" ]; then
        response=$(curl -s -w "\n%{http_code}" $headers "$API_URL$endpoint")
    else
        response=$(curl -s -w "\n%{http_code}" -X $method $headers \
            -H "Content-Type: application/json" \
            -d "$data" \
            "$API_URL$endpoint")
    fi

    http_code=$(echo "$response" | tail -n1)
    body=$(echo "$response" | sed '$d')

    if [ "$http_code" = "200" ] || [ "$http_code" = "201" ]; then
        if [ -n "$expected_text" ]; then
            if echo "$body" | grep -q "$expected_text"; then
                echo -e "${GREEN}✓ PASS${NC} (HTTP $http_code)"
                PASSED=$((PASSED + 1))
                return 0
            else
                echo -e "${RED}✗ FAIL${NC} (Expected text not found)"
                echo "  Body: $body"
                FAILED=$((FAILED + 1))
                return 1
            fi
        else
            echo -e "${GREEN}✓ PASS${NC} (HTTP $http_code)"
            PASSED=$((PASSED + 1))
            return 0
        fi
    else
        echo -e "${RED}✗ FAIL${NC} (HTTP $http_code)"
        echo "  Body: $body"
        FAILED=$((FAILED + 1))
        return 1
    fi
}

###############################################################################
# Main Test Suite
###############################################################################

echo "=================================================="
echo "Critical API Endpoints Test"
echo "=================================================="
echo "API URL: $API_URL"
echo "Time: $(date)"
echo ""

# Store admin token globally
ADMIN_TOKEN=""

echo "=== Authentication Tests ==="
echo ""

# Test 1: Admin Login
echo -n "1. Admin login... "
TOTAL=$((TOTAL + 1))
response=$(curl -s -w "\n%{http_code}" -X POST "$API_URL/admin/login" \
    -H "Content-Type: application/json" \
    -d "{\"email\":\"$ADMIN_EMAIL\",\"password\":\"$ADMIN_PASSWORD\"}")

http_code=$(echo "$response" | tail -n1)
body=$(echo "$response" | sed '$d')

if [ "$http_code" = "200" ]; then
    ADMIN_TOKEN=$(echo "$body" | grep -o '"token":"[^"]*' | cut -d'"' -f4)
    if [ -n "$ADMIN_TOKEN" ]; then
        echo -e "${GREEN}✓ PASS${NC} (Token received)"
        PASSED=$((PASSED + 1))
    else
        echo -e "${RED}✗ FAIL${NC} (No token in response)"
        echo "  Body: $body"
        FAILED=$((FAILED + 1))
    fi
else
    echo -e "${RED}✗ FAIL${NC} (HTTP $http_code)"
    echo "  Body: $body"
    FAILED=$((FAILED + 1))
fi

echo ""
echo "=== Core Booking System Tests ==="
echo ""

# Test 2: Venue Template
test_endpoint \
    "2. Get venue template" \
    "GET" \
    "/venue/template/1" \
    "" \
    "" \
    "sections"

# Test 3: Seat Availability
test_endpoint \
    "3. Seat availability" \
    "GET" \
    "/seats/availability/1" \
    "" \
    "" \
    "seats"

# Test 4: Events List
test_endpoint \
    "4. Events list" \
    "GET" \
    "/events" \
    "" \
    "" \
    "data"

echo ""
echo "=== Admin Endpoints Tests ==="
echo ""

if [ -z "$ADMIN_TOKEN" ]; then
    echo -e "${YELLOW}⚠ Skipping admin tests (no token)${NC}"
else
    # Test 5: Admin Dashboard
    test_endpoint \
        "5. Admin dashboard stats" \
        "GET" \
        "/admin/dashboard/stats" \
        "-H \"Authorization: Bearer $ADMIN_TOKEN\"" \
        "" \
        "revenue"

    # Test 6: Orders List
    test_endpoint \
        "6. Admin orders list" \
        "GET" \
        "/admin/orders" \
        "-H \"Authorization: Bearer $ADMIN_TOKEN\"" \
        "" \
        "data"

    # Test 7: Customers List
    test_endpoint \
        "7. Admin customers list" \
        "GET" \
        "/admin/customers" \
        "-H \"Authorization: Bearer $ADMIN_TOKEN\"" \
        "" \
        "data"

    # Test 8: Analytics
    test_endpoint \
        "8. Analytics dashboard" \
        "GET" \
        "/admin/analytics/dashboard" \
        "-H \"Authorization: Bearer $ADMIN_TOKEN\"" \
        "" \
        "total"
fi

echo ""
echo "=== Email System Tests ==="
echo ""

if [ -n "$ADMIN_TOKEN" ]; then
    # Test 9: Email Templates List
    test_endpoint \
        "9. Email templates list" \
        "GET" \
        "/admin/email/templates" \
        "-H \"Authorization: Bearer $ADMIN_TOKEN\"" \
        "" \
        "templates"
else
    echo -e "${YELLOW}⚠ Skipping email tests (no token)${NC}"
fi

echo ""
echo "=== Ticket System Tests ==="
echo ""

if [ -n "$ADMIN_TOKEN" ]; then
    # Test 10: Ticket Metrics
    test_endpoint \
        "10. Ticket metrics" \
        "GET" \
        "/admin/tickets/metrics" \
        "-H \"Authorization: Bearer $ADMIN_TOKEN\"" \
        "" \
        "total"
else
    echo -e "${YELLOW}⚠ Skipping ticket tests (no token)${NC}"
fi

echo ""
echo "=== Financial/Payment Tests ==="
echo ""

if [ -n "$ADMIN_TOKEN" ]; then
    # Test 11: Financial Reports
    test_endpoint \
        "11. Financial summary" \
        "GET" \
        "/admin/reports/financial-summary" \
        "-H \"Authorization: Bearer $ADMIN_TOKEN\"" \
        "" \
        "revenue"
else
    echo -e "${YELLOW}⚠ Skipping financial tests (no token)${NC}"
fi

echo ""
echo "=================================================="
echo "Test Summary"
echo "=================================================="
echo "Total Tests: $TOTAL"
echo -e "Passed: ${GREEN}$PASSED${NC}"
echo -e "Failed: ${RED}$FAILED${NC}"

if [ $FAILED -eq 0 ]; then
    echo ""
    echo -e "${GREEN}✓ All tests passed!${NC}"
    exit 0
else
    echo ""
    echo -e "${RED}✗ Some tests failed. Review output above.${NC}"
    exit 1
fi
