#!/bin/bash
# ============================================================================
# ShopDB Comprehensive Form Testing Script (Bash version)
# ============================================================================

BASE_URL="${1:-http://192.168.122.151:8080}"
TEST_TIMESTAMP=$(date +%Y%m%d_%H%M%S)
TEST_PREFIX="AUTOTEST_${TEST_TIMESTAMP}"

PASSED=0
FAILED=0
TOTAL=0

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

echo ""
echo -e "${CYAN}============================================${NC}"
echo -e "${CYAN}ShopDB Comprehensive Form Testing${NC}"
echo -e "${CYAN}Started: $(date)${NC}"
echo -e "${CYAN}Base URL: $BASE_URL${NC}"
echo -e "${CYAN}Test Prefix: $TEST_PREFIX${NC}"
echo -e "${CYAN}============================================${NC}"
echo ""

# Test function for page loads
test_page() {
    local url="$1"
    local name="$2"
    local expected="${3:-}"

    TOTAL=$((TOTAL + 1))

    response=$(curl -s -w "\n%{http_code}" --max-time 30 "$url" 2>/dev/null)
    http_code=$(echo "$response" | tail -n1)
    body=$(echo "$response" | sed '$d')

    if [[ "$http_code" == "200" ]]; then
        # Check for ASP errors
        if echo "$body" | grep -qiE "Microsoft VBScript|Error 500|ADODB\.|error '8"; then
            echo -e "[${RED}FAIL${NC}] $name - Contains ASP error"
            FAILED=$((FAILED + 1))
            return 1
        fi
        # Check expected content if specified
        if [[ -n "$expected" ]] && ! echo "$body" | grep -qi "$expected"; then
            echo -e "[${RED}FAIL${NC}] $name - Missing expected content"
            FAILED=$((FAILED + 1))
            return 1
        fi
        echo -e "[${GREEN}PASS${NC}] $name"
        PASSED=$((PASSED + 1))
        return 0
    else
        echo -e "[${RED}FAIL${NC}] $name - HTTP $http_code"
        FAILED=$((FAILED + 1))
        return 1
    fi
}

# Test function for form submissions
test_form() {
    local url="$1"
    local name="$2"
    shift 2
    local data="$@"

    TOTAL=$((TOTAL + 1))

    # Don't follow redirects - 302 is success for form submissions
    response=$(curl -s -w "\n%{http_code}" --max-time 30 -X POST -d "$data" "$url" 2>/dev/null)
    http_code=$(echo "$response" | tail -n1)
    body=$(echo "$response" | sed '$d')

    # Check for success (200 or 302 redirect)
    if [[ "$http_code" == "200" ]] || [[ "$http_code" == "302" ]]; then
        # Check for ASP errors in response
        if echo "$body" | grep -qiE "Microsoft VBScript|Error 500|ADODB\.|error '8"; then
            echo -e "[${RED}FAIL${NC}] $name - Contains ASP error"
            FAILED=$((FAILED + 1))
            return 1
        fi
        echo -e "[${GREEN}PASS${NC}] $name"
        PASSED=$((PASSED + 1))
        return 0
    else
        echo -e "[${RED}FAIL${NC}] $name - HTTP $http_code"
        FAILED=$((FAILED + 1))
        return 1
    fi
}

# ----------------------------------------------------------------------------
# 1. PAGE LOAD TESTS
# ----------------------------------------------------------------------------
echo -e "${YELLOW}--- PAGE LOAD TESTS ---${NC}"

test_page "$BASE_URL/default.asp" "Dashboard loads"
test_page "$BASE_URL/displaynotifications.asp" "Notifications list loads"
test_page "$BASE_URL/displayapplications.asp" "Applications list loads"
test_page "$BASE_URL/displayprinters.asp" "Printers list loads"
test_page "$BASE_URL/displaypcs.asp" "PCs list loads"
test_page "$BASE_URL/displaymachines.asp" "Equipment list loads"
test_page "$BASE_URL/networkdevices.asp" "Network devices loads"
test_page "$BASE_URL/displaysubnets.asp" "Subnets list loads"
test_page "$BASE_URL/displayknowledgebase.asp" "Knowledge base loads"
test_page "$BASE_URL/machinemap.asp" "Machine map loads"
test_page "$BASE_URL/printermap.asp" "Printer map loads"

echo ""

# ----------------------------------------------------------------------------
# 2. ADD FORM PAGE LOAD TESTS
# ----------------------------------------------------------------------------
echo -e "${YELLOW}--- ADD FORM PAGE LOAD TESTS ---${NC}"

test_page "$BASE_URL/addnotification.asp" "Add notification form loads"
test_page "$BASE_URL/addmachine.asp" "Add equipment form loads"
test_page "$BASE_URL/addprinter.asp" "Add printer form loads"
test_page "$BASE_URL/addsubnet.asp" "Add subnet form loads"
test_page "$BASE_URL/addapplication.asp" "Add application form loads"
test_page "$BASE_URL/addknowledgebase.asp" "Add KB article form loads"
test_page "$BASE_URL/addvendor.asp" "Add vendor form loads"
test_page "$BASE_URL/addmodel.asp" "Add model form loads"
test_page "$BASE_URL/deviceaccesspoint.asp" "Add access point form loads"
test_page "$BASE_URL/deviceswitch.asp" "Add switch form loads"
test_page "$BASE_URL/devicecamera.asp" "Add camera form loads"
test_page "$BASE_URL/deviceidf.asp" "Add IDF form loads"
test_page "$BASE_URL/deviceserver.asp" "Add server form loads"

echo ""

# ----------------------------------------------------------------------------
# 3. NOTIFICATION FORM TESTS
# ----------------------------------------------------------------------------
echo -e "${YELLOW}--- NOTIFICATION FORM TESTS ---${NC}"

STARTTIME=$(date -u +"%Y-%m-%dT%H:%M")
ENDTIME=$(date -u -d "+1 day" +"%Y-%m-%dT%H:%M")

test_form "$BASE_URL/savenotification.asp" "Create notification (basic)" \
    "notification=${TEST_PREFIX}+-+Test+notification&notificationtypeid=2&businessunitid=&appid=&ticketnumber=GETEST123&starttime=${STARTTIME}&endtime=${ENDTIME}&isactive=1&isshopfloor=0"

echo ""

# ----------------------------------------------------------------------------
# 4. EQUIPMENT FORM TESTS
# ----------------------------------------------------------------------------
echo -e "${YELLOW}--- EQUIPMENT FORM TESTS ---${NC}"

test_form "$BASE_URL/savemachine.asp" "Create equipment" \
    "machinenumber=${TEST_PREFIX}-EQ001&modelid=1&businessunitid=1&alias=Test+Equipment&machinenotes=Automated+test&ip1=192.168.99.101&mac1=00:11:22:33:44:55&ip2=&mac2=&ip3=&mac3=&controllingpc=&dualpathid=&thirdpartymanaged=0&mapleft=&maptop="

echo ""

# ----------------------------------------------------------------------------
# 5. PRINTER FORM TESTS
# ----------------------------------------------------------------------------
echo -e "${YELLOW}--- PRINTER FORM TESTS ---${NC}"

test_form "$BASE_URL/saveprinter.asp" "Create printer" \
    "printercsfname=${TEST_PREFIX}-PRN001&printerwindowsname=TestPrinter&modelid=1&serialnumber=TESTPRN123&ipaddress=192.168.99.201&fqdn=testprinter.test.local&machineid=&mapleft=&maptop="

echo ""

# ----------------------------------------------------------------------------
# 6. SUBNET FORM TESTS
# ----------------------------------------------------------------------------
echo -e "${YELLOW}--- SUBNET FORM TESTS ---${NC}"

test_form "$BASE_URL/addsubnetbackend.asp" "Create subnet" \
    "ipstart=192.168.99.0&cidr=24&vlan=999&subnettypeid=1&description=${TEST_PREFIX}+-+Test+subnet"

echo ""

# ----------------------------------------------------------------------------
# 7. APPLICATION FORM TESTS
# ----------------------------------------------------------------------------
echo -e "${YELLOW}--- APPLICATION FORM TESTS ---${NC}"

test_form "$BASE_URL/quickaddapplication.asp" "Create application" \
    "applicationname=${TEST_PREFIX}-App001&appdescription=Test+application&supportteamid=1&appownerid=&skilllevelid="

echo ""

# ----------------------------------------------------------------------------
# 8. KNOWLEDGE BASE FORM TESTS
# ----------------------------------------------------------------------------
echo -e "${YELLOW}--- KNOWLEDGE BASE FORM TESTS ---${NC}"

test_form "$BASE_URL/addlinkdirect.asp" "Create KB article" \
    "shortdescription=${TEST_PREFIX}+-+Test+KB&applicationid=1&keywords=test+automated&linkurl=https://example.com/test&topicid=1"

echo ""

# ----------------------------------------------------------------------------
# 9. VENDOR FORM TESTS
# ----------------------------------------------------------------------------
echo -e "${YELLOW}--- VENDOR FORM TESTS ---${NC}"

test_form "$BASE_URL/savevendor.asp" "Create vendor" \
    "vendor=${TEST_PREFIX}-Vendor001"

echo ""

# ----------------------------------------------------------------------------
# 10. MODEL FORM TESTS
# ----------------------------------------------------------------------------
echo -e "${YELLOW}--- MODEL FORM TESTS ---${NC}"

test_form "$BASE_URL/savemodel.asp" "Create model" \
    "modelnumber=${TEST_PREFIX}-Model001&vendorid=1&machinetypeid=1&notes=Test+model"

echo ""

# ----------------------------------------------------------------------------
# 11. NETWORK DEVICE FORM TESTS
# ----------------------------------------------------------------------------
echo -e "${YELLOW}--- NETWORK DEVICE FORM TESTS ---${NC}"

test_form "$BASE_URL/deviceaccesspoint.asp" "Create access point" \
    "type=new&apname=${TEST_PREFIX}-AP001&serialnumber=TESTAP123&ipaddress=192.168.99.50&fqdn=testap.test.local&modelid=&description=Test+AP&isactive=1&mapleft=&maptop="

test_form "$BASE_URL/deviceswitch.asp" "Create switch" \
    "type=new&alias=${TEST_PREFIX}-SW001&serialnumber=TESTSW123&ipaddress=192.168.99.51&fqdn=testsw.test.local&modelid=&machinenotes=Test+switch&isactive=1&mapleft=&maptop="

test_form "$BASE_URL/devicecamera.asp" "Create camera" \
    "type=new&alias=${TEST_PREFIX}-CAM001&serialnumber=TESTCAM123&ipaddress=192.168.99.52&fqdn=testcam.test.local&modelid=&machinenotes=Test+camera&isactive=1&mapleft=&maptop="

test_form "$BASE_URL/deviceidf.asp" "Create IDF" \
    "type=new&alias=${TEST_PREFIX}-IDF001&serialnumber=TESTIDF123&ipaddress=192.168.99.53&fqdn=testidf.test.local&modelid=&machinenotes=Test+IDF&isactive=1&mapleft=&maptop="

test_form "$BASE_URL/deviceserver.asp" "Create server" \
    "type=new&alias=${TEST_PREFIX}-SRV001&serialnumber=TESTSRV123&fqdn=testsrv.test.local&modelid=&machinenotes=Test+server&isactive=1&mapleft=&maptop="

echo ""

# ----------------------------------------------------------------------------
# 12. API ENDPOINT TESTS
# ----------------------------------------------------------------------------
echo -e "${YELLOW}--- API ENDPOINT TESTS ---${NC}"

test_page "$BASE_URL/api.asp?action=getDashboardData" "API getDashboardData" "success"
test_page "$BASE_URL/api.asp?action=getShopfloorPCs" "API getShopfloorPCs" "success"
test_page "$BASE_URL/apiprinters.asp" "API printers" "printerid"
test_page "$BASE_URL/apibusinessunits.asp" "API business units" "businessunit"

echo ""

# ============================================================================
# SUMMARY
# ============================================================================
echo -e "${CYAN}============================================${NC}"
echo -e "${CYAN}TEST SUMMARY${NC}"
echo -e "${CYAN}============================================${NC}"
echo ""
echo "Total Tests: $TOTAL"
echo -e "Passed: ${GREEN}$PASSED${NC}"
if [[ $FAILED -gt 0 ]]; then
    echo -e "Failed: ${RED}$FAILED${NC}"
else
    echo -e "Failed: ${GREEN}$FAILED${NC}"
fi
echo ""

# ============================================================================
# CLEANUP SQL
# ============================================================================
echo -e "${YELLOW}--- CLEANUP SQL ---${NC}"
echo "Run this SQL to clean up test data:"
echo ""
echo "DELETE FROM communications WHERE machineid IN (SELECT machineid FROM machines WHERE machinenumber LIKE '${TEST_PREFIX}%' OR alias LIKE '${TEST_PREFIX}%');"
echo "DELETE FROM notifications WHERE notification LIKE '${TEST_PREFIX}%';"
echo "DELETE FROM machines WHERE machinenumber LIKE '${TEST_PREFIX}%' OR alias LIKE '${TEST_PREFIX}%';"
echo "DELETE FROM printers WHERE printercsfname LIKE '${TEST_PREFIX}%';"
echo "DELETE FROM subnets WHERE description LIKE '${TEST_PREFIX}%';"
echo "DELETE FROM applications WHERE applicationname LIKE '${TEST_PREFIX}%';"
echo "DELETE FROM knowledgebase WHERE shortdescription LIKE '${TEST_PREFIX}%';"
echo "DELETE FROM vendors WHERE vendor LIKE '${TEST_PREFIX}%';"
echo "DELETE FROM models WHERE modelnumber LIKE '${TEST_PREFIX}%';"
echo ""
echo -e "${CYAN}Testing completed at $(date)${NC}"
echo -e "${YELLOW}Test prefix: $TEST_PREFIX${NC}"

# Exit with failure if any tests failed
[[ $FAILED -eq 0 ]] && exit 0 || exit 1
