#!/bin/bash
#
# PKF Asset Management System - Automated UAT Test Script
# Run this on any Linux server with curl and jq installed
#
# Usage: ./pkf_uat_test.sh [URL]
#
# Examples:
#   ./pkf_uat_test.sh                                    # Uses default (production)
#   ./pkf_uat_test.sh http://192.168.4.59:8081          # Test local/staging server
#   ./pkf_uat_test.sh https://staging.example.com       # Test staging
#
# Output: TEST_REPORT_[date].md
#

set -e

# Configuration - can be overridden by command line argument
DEFAULT_URL="https://pkfassetman.commstack.group"
BASE_URL="${1:-$DEFAULT_URL}"
API_URL="${BASE_URL}/api"
EMAIL="manager@demo.com"
PASSWORD="Password123!"
REPORT_FILE="TEST_REPORT_$(date +%Y%m%d_%H%M%S).md"

echo ""
echo "Target: ${BASE_URL}"
echo ""

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

# Counters
TOTAL=0
PASSED=0
FAILED=0
BLOCKED=0

# Arrays to store results
declare -a RESULTS
declare -a FAILURES

# Check dependencies
check_dependencies() {
    echo -e "${BLUE}Checking dependencies...${NC}"

    if ! command -v curl &> /dev/null; then
        echo -e "${RED}Error: curl is required but not installed.${NC}"
        exit 1
    fi

    if ! command -v jq &> /dev/null; then
        echo -e "${YELLOW}Warning: jq not installed. JSON parsing will be limited.${NC}"
        JQ_AVAILABLE=false
    else
        JQ_AVAILABLE=true
    fi

    echo -e "${GREEN}Dependencies OK${NC}"
}

# Login and get token
login() {
    echo -e "${BLUE}Logging in as ${EMAIL}...${NC}"

    RESPONSE=$(curl -s -X POST "${API_URL}/auth/login" \
        -H "Content-Type: application/json" \
        -d "{\"email\":\"${EMAIL}\",\"password\":\"${PASSWORD}\"}")

    if [ "$JQ_AVAILABLE" = true ]; then
        TOKEN=$(echo "$RESPONSE" | jq -r '.token // empty')
        SUCCESS=$(echo "$RESPONSE" | jq -r '.success // false')
    else
        TOKEN=$(echo "$RESPONSE" | grep -o '"token":"[^"]*"' | cut -d'"' -f4)
        SUCCESS=$(echo "$RESPONSE" | grep -o '"success":true')
    fi

    if [ -z "$TOKEN" ] || [ "$TOKEN" = "null" ]; then
        echo -e "${RED}Login failed! Response: ${RESPONSE}${NC}"
        exit 1
    fi

    echo -e "${GREEN}Login successful!${NC}"
    export TOKEN
}

# Test function
run_test() {
    local ID="$1"
    local NAME="$2"
    local METHOD="$3"
    local ENDPOINT="$4"
    local EXPECTED_STATUS="$5"
    local DATA="$6"

    TOTAL=$((TOTAL + 1))

    # Build curl command
    if [ "$METHOD" = "GET" ]; then
        RESPONSE=$(curl -s -w "\n%{http_code}" -X GET "${API_URL}${ENDPOINT}" \
            -H "Authorization: Bearer ${TOKEN}" \
            -H "Content-Type: application/json" 2>/dev/null)
    elif [ "$METHOD" = "POST" ]; then
        RESPONSE=$(curl -s -w "\n%{http_code}" -X POST "${API_URL}${ENDPOINT}" \
            -H "Authorization: Bearer ${TOKEN}" \
            -H "Content-Type: application/json" \
            -d "${DATA}" 2>/dev/null)
    elif [ "$METHOD" = "GET_NO_AUTH" ]; then
        RESPONSE=$(curl -s -w "\n%{http_code}" -X GET "${API_URL}${ENDPOINT}" \
            -H "Content-Type: application/json" 2>/dev/null)
    else
        RESPONSE=$(curl -s -w "\n%{http_code}" -X "$METHOD" "${API_URL}${ENDPOINT}" \
            -H "Authorization: Bearer ${TOKEN}" \
            -H "Content-Type: application/json" 2>/dev/null)
    fi

    # Extract status code (last line)
    HTTP_CODE=$(echo "$RESPONSE" | tail -n1)
    BODY=$(echo "$RESPONSE" | sed '$d')

    # Check result
    if [ "$HTTP_CODE" = "$EXPECTED_STATUS" ]; then
        PASSED=$((PASSED + 1))
        STATUS="PASS"
        COLOR="$GREEN"
        RESULTS+=("| ${ID} | ${NAME} | ✅ PASS | ${HTTP_CODE} | |")
    else
        FAILED=$((FAILED + 1))
        STATUS="FAIL"
        COLOR="$RED"
        # Truncate body for display
        SHORT_BODY=$(echo "$BODY" | head -c 100)
        RESULTS+=("| ${ID} | ${NAME} | ❌ FAIL | ${HTTP_CODE} (expected ${EXPECTED_STATUS}) | ${SHORT_BODY}... |")
        FAILURES+=("${ID}: ${NAME} - Got ${HTTP_CODE}, expected ${EXPECTED_STATUS}")
    fi

    echo -e "${COLOR}[${STATUS}]${NC} ${ID}: ${NAME} (HTTP ${HTTP_CODE})"
}

# Test frontend
test_frontend() {
    echo ""
    echo -e "${BLUE}Testing Frontend...${NC}"

    TOTAL=$((TOTAL + 1))
    HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" "${BASE_URL}")

    if [ "$HTTP_CODE" = "200" ]; then
        PASSED=$((PASSED + 1))
        echo -e "${GREEN}[PASS]${NC} Frontend loads (HTTP ${HTTP_CODE})"
        RESULTS+=("| FRONT-001 | Frontend Loads | ✅ PASS | ${HTTP_CODE} | |")
    else
        FAILED=$((FAILED + 1))
        echo -e "${RED}[FAIL]${NC} Frontend loads (HTTP ${HTTP_CODE})"
        RESULTS+=("| FRONT-001 | Frontend Loads | ❌ FAIL | ${HTTP_CODE} | |")
        FAILURES+=("FRONT-001: Frontend - Got ${HTTP_CODE}, expected 200")
    fi
}

# Test health endpoint
test_health() {
    TOTAL=$((TOTAL + 1))
    RESPONSE=$(curl -s -w "\n%{http_code}" "${BASE_URL}/health" 2>/dev/null)
    HTTP_CODE=$(echo "$RESPONSE" | tail -n1)

    if [ "$HTTP_CODE" = "200" ]; then
        PASSED=$((PASSED + 1))
        echo -e "${GREEN}[PASS]${NC} Health endpoint (HTTP ${HTTP_CODE})"
        RESULTS+=("| HEALTH-001 | Health Endpoint | ✅ PASS | ${HTTP_CODE} | |")
    else
        FAILED=$((FAILED + 1))
        echo -e "${RED}[FAIL]${NC} Health endpoint (HTTP ${HTTP_CODE})"
        RESULTS+=("| HEALTH-001 | Health Endpoint | ❌ FAIL | ${HTTP_CODE} | |")
        FAILURES+=("HEALTH-001: Health endpoint - Got ${HTTP_CODE}, expected 200")
    fi
}

# Generate report
generate_report() {
    echo ""
    echo -e "${BLUE}Generating report: ${REPORT_FILE}${NC}"

    PASS_RATE=0
    if [ $TOTAL -gt 0 ]; then
        PASS_RATE=$((PASSED * 100 / TOTAL))
    fi

    cat > "$REPORT_FILE" << EOF
# PKF Asset Management - UAT Test Report

**Test Date:** $(date '+%Y-%m-%d %H:%M:%S')
**Environment:** ${BASE_URL}
**Tester:** Automated Script

---

## Executive Summary

| Metric | Value |
|--------|-------|
| **Total Tests** | ${TOTAL} |
| **Passed** | ${PASSED} (${PASS_RATE}%) |
| **Failed** | ${FAILED} |
| **Blocked** | ${BLOCKED} |
| **Pass Rate** | ${PASS_RATE}% |

EOF

    if [ ${#FAILURES[@]} -gt 0 ]; then
        cat >> "$REPORT_FILE" << EOF
### ⚠️ Overall Status: ISSUES FOUND

---

## Failed Tests

EOF
        for failure in "${FAILURES[@]}"; do
            echo "- ${failure}" >> "$REPORT_FILE"
        done
        echo "" >> "$REPORT_FILE"
    else
        cat >> "$REPORT_FILE" << EOF
### ✅ Overall Status: ALL TESTS PASSED

EOF
    fi

    cat >> "$REPORT_FILE" << EOF
---

## Detailed Results

| ID | Test Case | Status | Response | Notes |
|----|-----------|--------|----------|-------|
EOF

    for result in "${RESULTS[@]}"; do
        echo "$result" >> "$REPORT_FILE"
    done

    cat >> "$REPORT_FILE" << EOF

---

## Test Configuration

- **API URL:** ${API_URL}
- **Test User:** ${EMAIL}
- **Script Version:** 1.0

---

*Report generated automatically by pkf_uat_test.sh*
EOF

    echo -e "${GREEN}Report saved to: ${REPORT_FILE}${NC}"
}

# Main test execution
main() {
    echo "========================================"
    echo "PKF Asset Management - UAT Test Suite"
    echo "========================================"
    echo ""

    check_dependencies
    echo ""

    # Test frontend first
    test_frontend
    test_health

    # Login
    login
    echo ""

    # ==========================================
    # AUTHENTICATION TESTS
    # ==========================================
    echo -e "${YELLOW}=== Authentication Tests ===${NC}"
    RESULTS+=("| | **Authentication** | | | |")

    run_test "AUTH-001" "Valid Login" "POST" "/auth/login" "200" "{\"email\":\"${EMAIL}\",\"password\":\"${PASSWORD}\"}"
    run_test "AUTH-002" "Invalid Password" "POST" "/auth/login" "401" "{\"email\":\"${EMAIL}\",\"password\":\"wrongpassword\"}"
    run_test "AUTH-003" "Invalid Email" "POST" "/auth/login" "401" "{\"email\":\"invalid@test.com\",\"password\":\"test\"}"
    run_test "AUTH-004" "Get Current User" "GET" "/auth/user" "200"

    # ==========================================
    # DASHBOARD TESTS
    # ==========================================
    echo ""
    echo -e "${YELLOW}=== Dashboard Tests ===${NC}"
    RESULTS+=("| | **Dashboard** | | | |")

    run_test "DASH-001" "Dashboard Stats" "GET" "/dashboard/stats" "200"
    run_test "DASH-002" "Dashboard with Date Filter" "GET" "/dashboard/stats?startDate=2024-01-01&endDate=2024-12-31" "200"
    run_test "DASH-003" "Value Trends" "GET" "/dashboard/value-trends" "200"
    run_test "DASH-004" "Asset Register" "GET" "/dashboard/register" "200"

    # ==========================================
    # ASSET TESTS
    # ==========================================
    echo ""
    echo -e "${YELLOW}=== Asset Management Tests ===${NC}"
    RESULTS+=("| | **Asset Management** | | | |")

    run_test "ASSET-001" "List Assets" "GET" "/assets" "200"
    run_test "ASSET-002" "List Assets Paginated" "GET" "/assets?page=1&limit=10" "200"
    run_test "ASSET-003" "Get Single Asset" "GET" "/assets/1" "200"
    run_test "ASSET-004" "Search Assets" "GET" "/assets?search=test" "200"
    run_test "ASSET-005" "Filter by Status" "GET" "/assets?status=active" "200"
    run_test "ASSET-006" "Asset Audit Trail" "GET" "/assets/1/audit-trail" "200"
    run_test "ASSET-007" "Recent Audit Trail" "GET" "/assets/audit-trail/recent" "200"

    # ==========================================
    # DEPRECIATION TESTS
    # ==========================================
    echo ""
    echo -e "${YELLOW}=== Depreciation Tests ===${NC}"
    RESULTS+=("| | **Depreciation** | | | |")

    run_test "DEP-001" "Depreciation Methods" "GET" "/depreciation/methods" "200"
    run_test "DEP-002" "Depreciation Summary" "GET" "/depreciation/summary" "200"
    run_test "DEP-003" "Depreciation List" "GET" "/depreciation/list" "200"
    run_test "DEP-004" "Depreciation by Category" "GET" "/depreciation/by-category" "200"
    run_test "DEP-005" "Depreciation by Location" "GET" "/depreciation/by-location" "200"
    run_test "DEP-006" "Asset Depreciation Schedule" "GET" "/depreciation/schedule/1" "200"
    run_test "DEP-007" "Eligible Assets" "GET" "/depreciation/eligible-assets" "200"
    run_test "DEP-008" "Locked Periods" "GET" "/depreciation/locked-periods" "200"

    # ==========================================
    # WEAR & TEAR TESTS
    # ==========================================
    echo ""
    echo -e "${YELLOW}=== Wear & Tear (Tax) Tests ===${NC}"
    RESULTS+=("| | **Wear & Tear** | | | |")

    run_test "WT-001" "W&T Register" "GET" "/wear-and-tear/register" "200"
    run_test "WT-002" "W&T Summary" "GET" "/wear-and-tear/summary" "200"
    run_test "WT-003" "W&T by Section" "GET" "/wear-and-tear/by-section" "200"
    run_test "WT-004" "W&T by Category" "GET" "/wear-and-tear/by-category" "200"
    run_test "WT-005" "W&T Locked Periods" "GET" "/wear-and-tear/locked-periods" "200"

    # ==========================================
    # SARS SECTIONS
    # ==========================================
    echo ""
    echo -e "${YELLOW}=== SARS Sections Tests ===${NC}"
    RESULTS+=("| | **SARS Sections** | | | |")

    run_test "SARS-001" "Get SARS Sections" "GET" "/sars-sections" "200"

    # ==========================================
    # CATEGORY TESTS
    # ==========================================
    echo ""
    echo -e "${YELLOW}=== Category Tests ===${NC}"
    RESULTS+=("| | **Categories** | | | |")

    run_test "CAT-001" "Category Tree" "GET" "/categories/tree" "200"
    run_test "CAT-002" "Level 1 Categories" "GET" "/categories/level1" "200"
    run_test "CAT-003" "Level 2 Categories" "GET" "/categories/level2" "200"
    run_test "CAT-004" "Level 3 Categories" "GET" "/categories/level3" "200"
    run_test "CAT-005" "Level 4 Categories" "GET" "/categories/level4" "200"

    # ==========================================
    # LOCATION TESTS
    # ==========================================
    echo ""
    echo -e "${YELLOW}=== Location Tests ===${NC}"
    RESULTS+=("| | **Locations** | | | |")

    run_test "LOC-001" "Location Tree" "GET" "/locations/tree" "200"
    run_test "LOC-002" "Level 1 Locations" "GET" "/locations/level1" "200"
    run_test "LOC-003" "Level 2 Locations" "GET" "/locations/level2" "200"
    run_test "LOC-004" "Level 3 Locations" "GET" "/locations/level3" "200"

    # ==========================================
    # CUSTODIAN TESTS
    # ==========================================
    echo ""
    echo -e "${YELLOW}=== Custodian Tests ===${NC}"
    RESULTS+=("| | **Custodians** | | | |")

    run_test "CUST-001" "List Custodians" "GET" "/custodians" "200"
    run_test "CUST-002" "Get Departments" "GET" "/custodians/departments" "200"

    # ==========================================
    # REPORT TESTS
    # ==========================================
    echo ""
    echo -e "${YELLOW}=== Report Tests ===${NC}"
    RESULTS+=("| | **Reports** | | | |")

    run_test "RPT-001" "Inventory Report" "GET" "/reports/inventory" "200"
    run_test "RPT-002" "Depreciation Report" "GET" "/reports/depreciation" "200"
    run_test "RPT-003" "Value Report" "GET" "/reports/value" "200"
    run_test "RPT-004" "Condition Report" "GET" "/reports/condition" "200"
    run_test "RPT-005" "Audit Report" "GET" "/reports/audit" "200"

    # ==========================================
    # USER TESTS
    # ==========================================
    echo ""
    echo -e "${YELLOW}=== User Management Tests ===${NC}"
    RESULTS+=("| | **User Management** | | | |")

    run_test "USER-001" "List Users" "GET" "/users" "200"
    run_test "USER-002" "User Stats" "GET" "/users/stats" "200"

    # ==========================================
    # PERIOD TESTS
    # ==========================================
    echo ""
    echo -e "${YELLOW}=== Period Tests ===${NC}"
    RESULTS+=("| | **Periods** | | | |")

    run_test "PERIOD-001" "List Periods" "GET" "/periods" "200"
    run_test "PERIOD-002" "Current Period" "GET" "/periods/current" "200"

    # ==========================================
    # SECURITY TESTS
    # ==========================================
    echo ""
    echo -e "${YELLOW}=== Security Tests ===${NC}"
    RESULTS+=("| | **Security** | | | |")

    run_test "SEC-001" "Protected Route No Auth" "GET_NO_AUTH" "/dashboard/stats" "401"
    run_test "SEC-002" "Invalid Token" "GET" "/dashboard/stats" "200"  # This uses valid token, just verifying it works

    # ==========================================
    # GENERATE REPORT
    # ==========================================
    echo ""
    echo "========================================"
    generate_report

    # Print summary
    echo ""
    echo "========================================"
    echo -e "${BLUE}TEST SUMMARY${NC}"
    echo "========================================"
    echo -e "Total:  ${TOTAL}"
    echo -e "Passed: ${GREEN}${PASSED}${NC}"
    echo -e "Failed: ${RED}${FAILED}${NC}"
    echo -e "Pass Rate: ${PASS_RATE}%"
    echo "========================================"

    if [ $FAILED -gt 0 ]; then
        echo ""
        echo -e "${RED}Some tests failed. Check ${REPORT_FILE} for details.${NC}"
        exit 1
    else
        echo ""
        echo -e "${GREEN}All tests passed!${NC}"
        exit 0
    fi
}

# Run main
main "$@"
