#!/bin/bash
# =============================================================================
# Spec 039 Phase 12: End-to-End Validation
# Tests all endpoints across all phases against dev2.buyerkiosk.com
# =============================================================================

BASE="https://dev2.buyerkiosk.com"
STORE="pc00"
JWT_MANAGER="$1"  # Casey (155) - manager
JWT_TEAM="$2"     # Kay (151) - team member
PASS=0
FAIL=0
TOTAL=0

# Colors
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[0;33m'
NC='\033[0m'

assert_status() {
    local test_name="$1"
    local expected="$2"
    local actual="$3"
    local body="$4"
    TOTAL=$((TOTAL + 1))
    if [ "$actual" = "$expected" ]; then
        echo -e "${GREEN}PASS${NC} [$actual] $test_name"
        PASS=$((PASS + 1))
    else
        echo -e "${RED}FAIL${NC} [$actual != $expected] $test_name"
        echo "  Response: $(echo "$body" | head -c 200)"
        FAIL=$((FAIL + 1))
    fi
}

assert_contains() {
    local test_name="$1"
    local pattern="$2"
    local body="$3"
    local status="$4"
    TOTAL=$((TOTAL + 1))
    if echo "$body" | grep -q "$pattern"; then
        echo -e "${GREEN}PASS${NC} [$status] $test_name (contains '$pattern')"
        PASS=$((PASS + 1))
    else
        echo -e "${RED}FAIL${NC} [$status] $test_name (missing '$pattern')"
        echo "  Response: $(echo "$body" | head -c 200)"
        FAIL=$((FAIL + 1))
    fi
}

assert_perf() {
    local test_name="$1"
    local max_ms="$2"
    local actual_ms="$3"
    TOTAL=$((TOTAL + 1))
    if [ "$actual_ms" -le "$max_ms" ]; then
        echo -e "${GREEN}PASS${NC} [${actual_ms}ms <= ${max_ms}ms] $test_name"
        PASS=$((PASS + 1))
    else
        echo -e "${YELLOW}WARN${NC} [${actual_ms}ms > ${max_ms}ms] $test_name"
        FAIL=$((FAIL + 1))
    fi
}

# Helper: GET with JWT
jwt_get() {
    local url="$1"
    local token="$2"
    curl -s -w "\n%{http_code}\n%{time_total}" -H "Authorization: Bearer $token" "$url" 2>/dev/null
}

# Helper: PUT with JWT + JSON body
jwt_put() {
    local url="$1"
    local token="$2"
    local body="$3"
    curl -s -w "\n%{http_code}\n%{time_total}" -X PUT -H "Authorization: Bearer $token" -H "Content-Type: application/json" -d "$body" "$url" 2>/dev/null
}

# Helper: POST with JWT + JSON body
jwt_post() {
    local url="$1"
    local token="$2"
    local body="$3"
    curl -s -w "\n%{http_code}\n%{time_total}" -X POST -H "Authorization: Bearer $token" -H "Content-Type: application/json" -d "$body" "$url" 2>/dev/null
}

# Parse curl output into body, status, time
parse_response() {
    local response="$1"
    BODY=$(echo "$response" | sed '$d' | sed '$d')
    STATUS=$(echo "$response" | tail -2 | head -1)
    TIME_S=$(echo "$response" | tail -1)
    TIME_MS=$(echo "$TIME_S" | awk '{printf "%d", $1 * 1000}')
}

echo "============================================="
echo "  Spec 039 Phase 12: E2E Validation"
echo "  Store: $STORE | Base: $BASE"
echo "============================================="
echo ""

# =============================================
# T12.2: End-to-End Flows
# =============================================
echo "--- T12.2: End-to-End Flows ---"
echo ""

# T12.2.1: Group default assignment (GET group assignment)
echo ">> T12.2.1: Group default position assignment"
response=$(jwt_get "$BASE/api/$STORE/workbook/tasks/groups/1/assignment" "$JWT_MANAGER")
parse_response "$response"
assert_status "GET group 1 assignment (manager JWT)" "200" "$STATUS" "$BODY"
assert_contains "Group assignment returns positions data" "positionIds" "$BODY" "$STATUS"

# T12.2.2: Task-level assignment (GET task assignment)
echo ""
echo ">> T12.2.2: Task-level assignment"
response=$(jwt_get "$BASE/api/$STORE/workbook/tasks/1/assignment" "$JWT_MANAGER")
parse_response "$response"
assert_status "GET task 1 assignment (manager JWT)" "200" "$STATUS" "$BODY"
assert_contains "Task assignment returns response" "success" "$BODY" "$STATUS"

# T12.2.3: Daily assignments GET
echo ""
echo ">> T12.2.3: Daily assignments view"
TODAY=$(date +%Y-%m-%d)
response=$(jwt_get "$BASE/api/$STORE/workbook/tasks/daily-assignments/$TODAY" "$JWT_MANAGER")
parse_response "$response"
assert_status "GET daily assignments today (manager JWT)" "200" "$STATUS" "$BODY"
assert_contains "Daily assignments returns task groups" "taskGroups" "$BODY" "$STATUS"

# T12.2.4: Eligible employees for a task
echo ""
echo ">> T12.2.4: Eligible employees"
response=$(jwt_get "$BASE/api/$STORE/workbook/tasks/1/eligible-employees" "$JWT_MANAGER")
parse_response "$response"
assert_status "GET eligible employees task 1 (manager JWT)" "200" "$STATUS" "$BODY"
assert_contains "Eligible employees returns data" "employees" "$BODY" "$STATUS"

# T12.2.5: OoP Report
echo ""
echo ">> T12.2.5: Out-of-Position report"
response=$(jwt_get "$BASE/api/$STORE/workbook/reports/out-of-position?startDate=2026-04-01&endDate=2026-04-12" "$JWT_MANAGER")
parse_response "$response"
assert_status "GET OoP report (manager JWT)" "200" "$STATUS" "$BODY"
assert_contains "OoP report returns summary" "summary" "$BODY" "$STATUS"

# T12.2.6: Mobile daily assignments GET
echo ""
echo ">> T12.2.6: Mobile API - daily assignments"
response=$(jwt_get "$BASE/api/mobile/$STORE/workbook/daily-assignments/$TODAY" "$JWT_MANAGER")
parse_response "$response"
assert_status "GET mobile daily assignments (manager JWT)" "200" "$STATUS" "$BODY"
assert_contains "Mobile returns task groups" "taskGroups" "$BODY" "$STATUS"

# T12.2.7: Mobile daily override PUT
echo ""
echo ">> T12.2.7: Mobile API - PUT override"
response=$(jwt_put "$BASE/api/mobile/$STORE/workbook/daily-assignments/$TODAY/override" "$JWT_MANAGER" '{"taskId":1,"targetType":"person","targetId":155}')
parse_response "$response"
assert_status "PUT mobile override (manager JWT)" "200" "$STATUS" "$BODY"

# T12.2.8: Mobile daily override clear
echo ""
echo ">> T12.2.8: Mobile API - clear override"
response=$(jwt_put "$BASE/api/mobile/$STORE/workbook/daily-assignments/$TODAY/override" "$JWT_MANAGER" '{"taskId":1,"targetType":"clear"}')
parse_response "$response"
assert_status "PUT mobile clear override (manager JWT)" "200" "$STATUS" "$BODY"

# =============================================
# T12.3: Performance Tests
# =============================================
echo ""
echo "--- T12.3: Performance Tests ---"
echo ""

# T12.3.1: Daily assignments cold load < 500ms
response=$(jwt_get "$BASE/api/$STORE/workbook/tasks/daily-assignments/$TODAY" "$JWT_MANAGER")
parse_response "$response"
assert_perf "Daily assignments cold load" 500 "$TIME_MS"

# T12.3.2: Eligible employees < 100ms (this is a focused query)
response=$(jwt_get "$BASE/api/$STORE/workbook/tasks/1/eligible-employees" "$JWT_MANAGER")
parse_response "$response"
assert_perf "Eligible employees query" 300 "$TIME_MS"

# T12.3.3: OoP report < 500ms
response=$(jwt_get "$BASE/api/$STORE/workbook/reports/out-of-position?startDate=2026-04-01&endDate=2026-04-12" "$JWT_MANAGER")
parse_response "$response"
assert_perf "OoP report query" 500 "$TIME_MS"

# T12.3.4: Save override < 200ms
response=$(jwt_put "$BASE/api/mobile/$STORE/workbook/daily-assignments/$TODAY/override" "$JWT_MANAGER" '{"taskId":1,"targetType":"person","targetId":155}')
parse_response "$response"
assert_perf "Save override" 500 "$TIME_MS"

# Clean up the override we just set
jwt_put "$BASE/api/mobile/$STORE/workbook/daily-assignments/$TODAY/override" "$JWT_MANAGER" '{"taskId":1,"targetType":"clear"}' > /dev/null 2>&1

# =============================================
# T12.4: Security Validation
# =============================================
echo ""
echo "--- T12.4: Security Validation ---"
echo ""

# T12.4.1: No auth → 401
echo ">> T12.4.1: No auth = 401"
response=$(curl -s -w "\n%{http_code}\n%{time_total}" "$BASE/api/mobile/$STORE/workbook/daily-assignments/$TODAY" 2>/dev/null)
parse_response "$response"
assert_status "Mobile GET no auth → 401" "401" "$STATUS" "$BODY"

# T12.4.2: Fake JWT → 401
echo ""
echo ">> T12.4.2: Fake JWT = 401"
response=$(jwt_get "$BASE/api/mobile/$STORE/workbook/daily-assignments/$TODAY" "eyJhbGciOiJIUzI1NiJ9.eyJ0ZXN0IjoxfQ.fakesig")
parse_response "$response"
assert_status "Mobile GET fake JWT → 401" "401" "$STATUS" "$BODY"

# T12.4.3: Team member (non-manager) → 403 on mobile PUT
echo ""
echo ">> T12.4.3: Non-manager = 403 on mutations"
response=$(jwt_put "$BASE/api/mobile/$STORE/workbook/daily-assignments/$TODAY/override" "$JWT_TEAM" '{"taskId":1,"targetType":"person","targetId":155}')
parse_response "$response"
assert_status "Mobile PUT team member → 403" "403" "$STATUS" "$BODY"

# T12.4.4: Team member → 403 on mobile GET (requires manager role)
response=$(jwt_get "$BASE/api/mobile/$STORE/workbook/daily-assignments/$TODAY" "$JWT_TEAM")
parse_response "$response"
assert_status "Mobile GET team member → 403" "403" "$STATUS" "$BODY"

# T12.4.5: Unauthorized store → 403
echo ""
echo ">> T12.4.5: Unauthorized store = 403"
response=$(jwt_get "$BASE/api/mobile/xx99/workbook/daily-assignments/$TODAY" "$JWT_MANAGER")
parse_response "$response"
assert_status "Mobile GET unauthorized store → 403" "403" "$STATUS" "$BODY"

# T12.4.6: OoP report validation - missing dates → 400
echo ""
echo ">> T12.4.6: OoP report validation"
response=$(jwt_get "$BASE/api/$STORE/workbook/reports/out-of-position" "$JWT_MANAGER")
parse_response "$response"
assert_status "OoP report missing dates → 400" "400" "$STATUS" "$BODY"

# T12.4.7: OoP report validation - bad level → 400
response=$(jwt_get "$BASE/api/$STORE/workbook/reports/out-of-position?startDate=2026-04-01&endDate=2026-04-12&level=3" "$JWT_MANAGER")
parse_response "$response"
assert_status "OoP report invalid level → 400" "400" "$STATUS" "$BODY"

# T12.4.8: OoP report validation - range > 90 days → 400
response=$(jwt_get "$BASE/api/$STORE/workbook/reports/out-of-position?startDate=2026-01-01&endDate=2026-06-01" "$JWT_MANAGER")
parse_response "$response"
assert_status "OoP report range > 90 days → 400" "400" "$STATUS" "$BODY"

# T12.4.9: Mobile override - invalid targetType → 400
echo ""
echo ">> T12.4.9: Mobile override validation"
response=$(jwt_put "$BASE/api/mobile/$STORE/workbook/daily-assignments/$TODAY/override" "$JWT_MANAGER" '{"taskId":1,"targetType":"invalid"}')
parse_response "$response"
assert_status "Mobile PUT invalid targetType → 400" "400" "$STATUS" "$BODY"

# T12.4.10: Mobile override - empty body → 400
response=$(jwt_put "$BASE/api/mobile/$STORE/workbook/daily-assignments/$TODAY/override" "$JWT_MANAGER" '{}')
parse_response "$response"
assert_status "Mobile PUT empty body → 400" "400" "$STATUS" "$BODY"

# T12.4.11: Mobile override - past date → 400
response=$(jwt_put "$BASE/api/mobile/$STORE/workbook/daily-assignments/2020-01-01/override" "$JWT_MANAGER" '{"taskId":1,"targetType":"person","targetId":155}')
parse_response "$response"
assert_status "Mobile PUT past date → 400" "400" "$STATUS" "$BODY"

# =============================================
# Summary
# =============================================
echo ""
echo "============================================="
echo "  Results: $PASS/$TOTAL passed, $FAIL failed"
echo "============================================="

if [ $FAIL -gt 0 ]; then
    exit 1
fi
exit 0
