#!/bin/bash

##############################################################################
# Package Display Test Suite Runner
#
# Runs all tests related to signup package selection and dashboard display
# Use this script to verify the package display functionality works correctly
##############################################################################

set -e  # Exit on error

echo "🧪 Package Display Test Suite"
echo "=============================="
echo ""

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

# Check if we're in the right directory
if [ ! -f "package.json" ]; then
    echo -e "${RED}❌ Error: package.json not found${NC}"
    echo "Please run this script from the mawidi-site directory"
    exit 1
fi

# Check if dev server is running
if ! curl -s http://localhost:9000/api/health > /dev/null 2>&1; then
    echo -e "${YELLOW}⚠️  Warning: Dev server not running on port 9000${NC}"
    echo "Starting dev server in background..."
    npm run dev > /dev/null 2>&1 &
    DEV_SERVER_PID=$!
    echo "Waiting for server to start..."
    sleep 10

    if ! curl -s http://localhost:9000/api/health > /dev/null 2>&1; then
        echo -e "${RED}❌ Failed to start dev server${NC}"
        exit 1
    fi
    echo -e "${GREEN}✅ Dev server started${NC}"
else
    echo -e "${GREEN}✅ Dev server is already running${NC}"
    DEV_SERVER_PID=""
fi

echo ""
echo "📋 Running Test Suites..."
echo ""

# Track results
TESTS_PASSED=0
TESTS_FAILED=0

##############################################################################
# Test 1: Unit Tests - API Endpoint
##############################################################################

echo -e "${BLUE}1️⃣  Running Unit Tests - Package Status API${NC}"
echo "   File: __tests__/api/user/package-status.test.ts"
echo ""

if npm run test:unit -- __tests__/api/user/package-status.test.ts; then
    echo -e "${GREEN}✅ API Unit Tests PASSED${NC}"
    ((TESTS_PASSED++))
else
    echo -e "${RED}❌ API Unit Tests FAILED${NC}"
    ((TESTS_FAILED++))
fi

echo ""
echo "---"
echo ""

##############################################################################
# Test 2: Integration Tests - Database Persistence
##############################################################################

echo -e "${BLUE}2️⃣  Running Integration Tests - Database Persistence${NC}"
echo "   File: __tests__/integration/signup-package-persistence.test.ts"
echo ""

if npm run test:unit -- __tests__/integration/signup-package-persistence.test.ts; then
    echo -e "${GREEN}✅ Integration Tests PASSED${NC}"
    ((TESTS_PASSED++))
else
    echo -e "${RED}❌ Integration Tests FAILED${NC}"
    ((TESTS_FAILED++))
fi

echo ""
echo "---"
echo ""

##############################################################################
# Test 3: Component Tests - BillingPanel UI
##############################################################################

echo -e "${BLUE}3️⃣  Running Component Tests - BillingPanel${NC}"
echo "   File: __tests__/components/BillingPanel.test.tsx"
echo ""

if npm run test:unit -- __tests__/components/BillingPanel.test.tsx; then
    echo -e "${GREEN}✅ Component Tests PASSED${NC}"
    ((TESTS_PASSED++))
else
    echo -e "${RED}❌ Component Tests FAILED${NC}"
    ((TESTS_FAILED++))
fi

echo ""
echo "---"
echo ""

##############################################################################
# Test 4: Regression Tests - Prevent Future Issues
##############################################################################

echo -e "${BLUE}4️⃣  Running Regression Tests - Package Display${NC}"
echo "   File: __tests__/regression/package-display-regression.test.ts"
echo ""

if npm run test:unit -- __tests__/regression/package-display-regression.test.ts; then
    echo -e "${GREEN}✅ Regression Tests PASSED${NC}"
    ((TESTS_PASSED++))
else
    echo -e "${RED}❌ Regression Tests FAILED${NC}"
    ((TESTS_FAILED++))
fi

echo ""
echo "---"
echo ""

##############################################################################
# Test 5: E2E Tests - Complete Signup Flow
##############################################################################

echo -e "${BLUE}5️⃣  Running E2E Tests - Signup Package Flow${NC}"
echo "   File: tests/signup-package-flow.spec.ts"
echo ""

if npm run test:e2e -- tests/signup-package-flow.spec.ts; then
    echo -e "${GREEN}✅ E2E Tests PASSED${NC}"
    ((TESTS_PASSED++))
else
    echo -e "${RED}❌ E2E Tests FAILED${NC}"
    ((TESTS_FAILED++))
fi

echo ""
echo "---"
echo ""

##############################################################################
# Test 6: Database Schema Verification
##############################################################################

echo -e "${BLUE}6️⃣  Running Database Schema Check${NC}"
echo ""

if npm run check:schema; then
    echo -e "${GREEN}✅ Database Schema Valid${NC}"
    ((TESTS_PASSED++))
else
    echo -e "${RED}❌ Database Schema Invalid${NC}"
    ((TESTS_FAILED++))
fi

echo ""
echo "---"
echo ""

##############################################################################
# Test 7: Manual API Test (if server running)
##############################################################################

echo -e "${BLUE}7️⃣  Testing API Endpoint Availability${NC}"
echo ""

# Test that both endpoints exist
echo "   Checking /api/subscription/details (old endpoint)..."
OLD_ENDPOINT_STATUS=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:9000/api/subscription/details || echo "000")

echo "   Checking /api/user/package-status (new endpoint)..."
NEW_ENDPOINT_STATUS=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:9000/api/user/package-status || echo "000")

if [ "$NEW_ENDPOINT_STATUS" != "000" ]; then
    echo -e "${GREEN}✅ New API endpoint exists (HTTP $NEW_ENDPOINT_STATUS)${NC}"
    ((TESTS_PASSED++))
else
    echo -e "${RED}❌ New API endpoint not found${NC}"
    ((TESTS_FAILED++))
fi

echo ""

##############################################################################
# Summary
##############################################################################

echo "=============================="
echo "📊 TEST SUMMARY"
echo "=============================="
echo ""
echo -e "Tests Passed: ${GREEN}$TESTS_PASSED${NC}"
echo -e "Tests Failed: ${RED}$TESTS_FAILED${NC}"
echo ""

if [ $TESTS_FAILED -eq 0 ]; then
    echo -e "${GREEN}✅ ALL TESTS PASSED${NC}"
    echo ""
    echo "🎉 Package display functionality is working correctly!"
    echo ""
    echo "The following scenarios are verified:"
    echo "  ✓ Package data saves to Prisma database"
    echo "  ✓ Package data syncs to Supabase database"
    echo "  ✓ Dashboard API reads selectedPackage field"
    echo "  ✓ UI displays pending payment state correctly"
    echo "  ✓ UI displays active subscription state correctly"
    echo "  ✓ Multi-language support works (Arabic + English)"
    echo "  ✓ All package tiers handled correctly"
    EXIT_CODE=0
else
    echo -e "${RED}❌ SOME TESTS FAILED${NC}"
    echo ""
    echo "⚠️  Please review the test output above to identify issues."
    echo ""
    echo "Common issues:"
    echo "  • Database not running (Prisma or Supabase)"
    echo "  • Schema mismatch between Prisma and Supabase"
    echo "  • Dev server not running on port 9000"
    echo "  • Missing environment variables"
    EXIT_CODE=1
fi

# Cleanup dev server if we started it
if [ ! -z "$DEV_SERVER_PID" ]; then
    echo ""
    echo "Stopping dev server (PID: $DEV_SERVER_PID)..."
    kill $DEV_SERVER_PID 2>/dev/null || true
fi

echo ""
echo "📖 For detailed test documentation, see:"
echo "   • SIGNUP_PACKAGE_FIX_SUMMARY.md"
echo "   • __tests__/api/user/package-status.test.ts"
echo "   • __tests__/regression/package-display-regression.test.ts"
echo ""

exit $EXIT_CODE
