#!/bin/bash
###############################################################################
# Test Script API Integration - Mercury QMS
# Server: 138.68.65.104 (quality.mercurysurgelati.org)
# 
# Usage:
#   chmod +x test-api.sh
#   ./test-api.sh [scenario]
#
# Scenarios:
#   all       - Run all tests
#   auth      - Test authentication
#   synthia   - Test Synthia Identity API
#   qms       - Test QMS API
#   slots     - Test Slot Dinamici API
#   fleetfix  - Test FleetFix API
#   audit     - Run full anagrafica audit scenario
###############################################################################

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

# Configuration
QMS_BASE_URL="${QMS_BASE_URL:-https://quality.mercurysurgelati.org}"
SYNTHIA_BASE_URL="${SYNTHIA_BASE_URL:-https://synthia.mercurysurgelati.org}"
FLEETFIX_BASE_URL="${FLEETFIX_BASE_URL:-https://fleetfix.mercurysurgelati.org}"
IDENTITY_URL="https://identity.synthia.mercurysurgelati.org"

# Bearer Token (will be obtained via OIDC)
BEARER_TOKEN=""
CLIENT_ID="${OIDC_CLIENT_ID:-qms_bridge}"
CLIENT_SECRET="${OIDC_CLIENT_SECRET}"

###############################################################################
# Utility Functions
###############################################################################

print_header() {
    echo -e "\n${BLUE}════════════════════════════════════════════════════════${NC}"
    echo -e "${BLUE}  $1${NC}"
    echo -e "${BLUE}════════════════════════════════════════════════════════${NC}\n"
}

print_test() {
    echo -e "${YELLOW}▶${NC} Testing: $1"
}

print_success() {
    echo -e "${GREEN}✅${NC} $1"
}

print_error() {
    echo -e "${RED}❌${NC} $1"
}

check_response() {
    local response=$1
    local test_name=$2
    
    if echo "$response" | jq -e '.success == true' > /dev/null 2>&1 || \
       echo "$response" | jq -e '.status == "healthy"' > /dev/null 2>&1; then
        print_success "$test_name - OK"
        return 0
    else
        print_error "$test_name - FAIL"
        echo "$response" | jq '.' 2>/dev/null || echo "$response"
        return 1
    fi
}

###############################################################################
# Authentication
###############################################################################

test_auth() {
    print_header "🔐 AUTHENTICATION TEST"
    
    if [ -z "$CLIENT_SECRET" ]; then
        print_error "OIDC_CLIENT_SECRET not set. Skipping authentication."
        return 1
    fi
    
    print_test "Obtaining OIDC token from Keycloak"
    
    local response=$(curl -s -X POST "${IDENTITY_URL}/realms/synthia/protocol/openid-connect/token" \
        -H "Content-Type: application/x-www-form-urlencoded" \
        -d "grant_type=client_credentials" \
        -d "client_id=${CLIENT_ID}" \
        -d "client_secret=${CLIENT_SECRET}" \
        -d "scope=tickets:write")
    
    BEARER_TOKEN=$(echo "$response" | jq -r '.access_token // empty')
    
    if [ -n "$BEARER_TOKEN" ] && [ "$BEARER_TOKEN" != "null" ]; then
        print_success "Token obtained successfully"
        echo "Token: ${BEARER_TOKEN:0:50}..."
        return 0
    else
        print_error "Failed to obtain token"
        echo "$response" | jq '.'
        return 1
    fi
}

###############################################################################
# Synthia Identity API Tests
###############################################################################

test_synthia() {
    print_header "👥 SYNTHIA IDENTITY API"
    
    # Test 1: Get All Tenants
    print_test "GET /api/v1/tenants"
    local response=$(curl -s -X GET "${SYNTHIA_BASE_URL}/api/v1/tenants" \
        -H "Authorization: Bearer ${BEARER_TOKEN}")
    check_response "$response" "Get All Tenants"
    
    # Test 2: Get Tenant Details
    print_test "GET /api/v1/tenants/acme_srl"
    response=$(curl -s -X GET "${SYNTHIA_BASE_URL}/api/v1/tenants/acme_srl" \
        -H "Authorization: Bearer ${BEARER_TOKEN}")
    check_response "$response" "Get Tenant Details"
    
    # Test 3: Get Users by Tenant
    print_test "GET /api/v1/users?tenantId=acme_srl"
    response=$(curl -s -X GET "${SYNTHIA_BASE_URL}/api/v1/users?tenantId=acme_srl" \
        -H "Authorization: Bearer ${BEARER_TOKEN}")
    check_response "$response" "Get Users by Tenant"
}

###############################################################################
# QMS API Tests
###############################################################################

test_qms() {
    print_header "🏭 QMS API - CONTROLLI QUALITÀ"
    
    # Test 1: Get Controls
    print_test "GET /api/qms/controls?siteId=site_001"
    local response=$(curl -s -X GET "${QMS_BASE_URL}/api/qms/controls?siteId=site_001" \
        -H "Authorization: Bearer ${BEARER_TOKEN}")
    check_response "$response" "Get Controls by Site"
    
    # Test 2: Get Nonconformities
    print_test "GET /api/qms/nonconformities?areaId=area_12"
    response=$(curl -s -X GET "${QMS_BASE_URL}/api/qms/nonconformities?areaId=area_12" \
        -H "Authorization: Bearer ${BEARER_TOKEN}")
    check_response "$response" "Get Nonconformities"
    
    # Test 3: Get Carichi
    print_test "GET /api/qms/carichi"
    response=$(curl -s -X GET "${QMS_BASE_URL}/api/qms/carichi" \
        -H "Authorization: Bearer ${BEARER_TOKEN}")
    check_response "$response" "Get Carichi in Arrivo"
}

###############################################################################
# Slot Dinamici API Tests
###############################################################################

test_slots() {
    print_header "⏱️ SLOT DINAMICI API"
    
    # Test 1: Health Check
    print_test "GET /api/slots/health"
    local response=$(curl -s -X GET "${QMS_BASE_URL}/api/slots/health")
    check_response "$response" "Health Check"
    
    # Test 2: Get Config
    print_test "GET /api/slots/config"
    response=$(curl -s -X GET "${QMS_BASE_URL}/api/slots/config")
    check_response "$response" "Get Config"
    echo "$response" | jq '.config' 2>/dev/null
    
    # Test 3: Calculate Duration
    print_test "POST /api/slots/calculate-duration (20 pallet SURGELATO)"
    response=$(curl -s -X POST "${QMS_BASE_URL}/api/slots/calculate-duration" \
        -H "Content-Type: application/json" \
        -d '{"num_pallet": 20, "tipo_prodotto": "SURGELATO"}')
    check_response "$response" "Calculate Duration"
    echo "$response" | jq '{duration: .duration_minutes, formula: .formula}' 2>/dev/null
    
    # Test 4: Allocate Slot
    print_test "POST /api/slots/allocate (16 pallet FRESCO)"
    local tomorrow=$(date -d "+1 day" +%Y-%m-%d)
    response=$(curl -s -X POST "${QMS_BASE_URL}/api/slots/allocate" \
        -H "Content-Type: application/json" \
        -d "{\"date\": \"${tomorrow}\", \"num_pallet\": 16, \"tipo_prodotto\": \"FRESCO\"}")
    check_response "$response" "Allocate Slot"
    echo "$response" | jq '.allocated_slot' 2>/dev/null
    
    # Test 5: Get Timeline
    print_test "GET /api/slots/timeline?date=${tomorrow}"
    response=$(curl -s -X GET "${QMS_BASE_URL}/api/slots/timeline?date=${tomorrow}")
    check_response "$response" "Get Timeline"
    echo "$response" | jq '{date: .date, total_slots: .total_slots, first_slot: .slots[0]}' 2>/dev/null
}

###############################################################################
# FleetFix API Tests
###############################################################################

test_fleetfix() {
    print_header "🧰 FLEETFIX API - TICKETING"
    
    # Test 1: Get Tickets
    print_test "GET /api/v1/tickets?buildingId=fabbr_x"
    local response=$(curl -s -X GET "${FLEETFIX_BASE_URL}/api/v1/tickets?buildingId=fabbr_x" \
        -H "Authorization: Bearer ${BEARER_TOKEN}")
    check_response "$response" "Get Tickets by Building"
    
    # Test 2: Get Building Details
    print_test "GET /api/v1/buildings/fabbr_x"
    response=$(curl -s -X GET "${QMS_BASE_URL}/api/v1/buildings/fabbr_x" \
        -H "Authorization: Bearer ${BEARER_TOKEN}")
    check_response "$response" "Get Building Details"
}

###############################################################################
# Full Audit Scenario
###############################################################################

test_audit_scenario() {
    print_header "🔍 FULL ANAGRAFICA AUDIT SCENARIO"
    
    echo -e "${YELLOW}Scenario:${NC} Audit completo dell'anagrafica con creazione NC e ticket"
    echo ""
    
    # Step 1: Get Tenants
    print_test "Step 1/4: Getting all tenants"
    local tenants=$(curl -s -X GET "${SYNTHIA_BASE_URL}/api/v1/tenants" \
        -H "Authorization: Bearer ${BEARER_TOKEN}")
    
    local tenant_id=$(echo "$tenants" | jq -r '.tenants[0].id // "acme_srl"')
    print_success "Found tenant: $tenant_id"
    
    # Step 2: Get Tenant Sites
    print_test "Step 2/4: Getting tenant sites"
    local tenant_details=$(curl -s -X GET "${SYNTHIA_BASE_URL}/api/v1/tenants/${tenant_id}" \
        -H "Authorization: Bearer ${BEARER_TOKEN}")
    
    local site_count=$(echo "$tenant_details" | jq '.tenant.sites | length // 0')
    print_success "Found $site_count sites"
    
    # Step 3: Create NC for missing coordinates
    print_test "Step 3/4: Creating NC for area without coordinates"
    local nc_response=$(curl -s -X POST "${QMS_BASE_URL}/api/qms/nonconformities" \
        -H "Authorization: Bearer ${BEARER_TOKEN}" \
        -H "Content-Type: application/json" \
        -d "{
            \"source\": \"anagrafica-audit\",
            \"areaId\": \"area_12\",
            \"description\": \"Area senza geo-coordinata - Test Audit\",
            \"priority\": \"medium\",
            \"tenantId\": \"${tenant_id}\",
            \"category\": \"INFRASTRUCTURE\"
        }")
    
    local nc_code=$(echo "$nc_response" | jq -r '.nonconformity.code // "N/A"')
    if [ "$nc_code" != "N/A" ]; then
        print_success "NC created: $nc_code"
    else
        print_error "Failed to create NC"
    fi
    
    # Step 4: Create FleetFix ticket
    print_test "Step 4/4: Creating FleetFix ticket for verification"
    local ticket_response=$(curl -s -X POST "${FLEETFIX_BASE_URL}/api/v1/tickets" \
        -H "Authorization: Bearer ${BEARER_TOKEN}" \
        -H "Content-Type: application/json" \
        -d "{
            \"title\": \"Verifica coordinate area_12 - Audit\",
            \"description\": \"NC ${nc_code}: Area richiede verifica coordinate GPS\",
            \"priority\": \"low\",
            \"category\": \"DATA_QUALITY\",
            \"buildingId\": \"fabbr_x\",
            \"areaId\": \"area_12\",
            \"tenantId\": \"${tenant_id}\",
            \"source\": \"anagrafica-audit\"
        }")
    
    local ticket_code=$(echo "$ticket_response" | jq -r '.ticket.code // "N/A"')
    if [ "$ticket_code" != "N/A" ]; then
        print_success "Ticket created: $ticket_code"
    else
        print_error "Failed to create ticket"
    fi
    
    echo ""
    print_header "📊 AUDIT SUMMARY"
    echo -e "Tenant:    ${GREEN}${tenant_id}${NC}"
    echo -e "Sites:     ${GREEN}${site_count}${NC}"
    echo -e "NC Code:   ${GREEN}${nc_code}${NC}"
    echo -e "Ticket:    ${GREEN}${ticket_code}${NC}"
}

###############################################################################
# Performance Test
###############################################################################

test_performance() {
    print_header "⚡ PERFORMANCE TEST"
    
    local endpoint="${QMS_BASE_URL}/api/slots/health"
    local iterations=10
    
    print_test "Running $iterations requests to $endpoint"
    
    local total_time=0
    local success_count=0
    
    for i in $(seq 1 $iterations); do
        local start=$(date +%s%N)
        local response=$(curl -s -w "\n%{http_code}" -X GET "$endpoint")
        local end=$(date +%s%N)
        
        local http_code=$(echo "$response" | tail -1)
        local duration=$(( (end - start) / 1000000 ))
        
        if [ "$http_code" = "200" ]; then
            ((success_count++))
            echo -e "  Request $i: ${GREEN}${duration}ms${NC} (HTTP $http_code)"
        else
            echo -e "  Request $i: ${RED}${duration}ms${NC} (HTTP $http_code)"
        fi
        
        total_time=$((total_time + duration))
    done
    
    local avg_time=$((total_time / iterations))
    
    echo ""
    print_success "Completed $success_count/$iterations requests"
    echo -e "Average response time: ${GREEN}${avg_time}ms${NC}"
}

###############################################################################
# Main
###############################################################################

show_help() {
    cat << EOF
Usage: $0 [scenario]

Scenarios:
  all         Run all tests (default)
  auth        Test authentication only
  synthia     Test Synthia Identity API
  qms         Test QMS API
  slots       Test Slot Dinamici API
  fleetfix    Test FleetFix API
  audit       Run full anagrafica audit scenario
  perf        Run performance test

Environment Variables:
  QMS_BASE_URL          QMS server URL (default: https://quality.mercurysurgelati.org)
  SYNTHIA_BASE_URL      Synthia server URL (default: https://synthia.mercurysurgelati.org)
  FLEETFIX_BASE_URL     FleetFix server URL (default: https://fleetfix.mercurysurgelati.org)
  OIDC_CLIENT_ID        OAuth client ID (default: qms_bridge)
  OIDC_CLIENT_SECRET    OAuth client secret (required for auth)

Examples:
  $0 all                # Run all tests
  $0 slots              # Test only slot APIs
  $0 audit              # Run audit scenario
  
  # With custom base URL:
  QMS_BASE_URL=http://localhost:8001 $0 slots

EOF
}

main() {
    local scenario="${1:-all}"
    
    if [ "$scenario" = "help" ] || [ "$scenario" = "-h" ] || [ "$scenario" = "--help" ]; then
        show_help
        exit 0
    fi
    
    echo -e "${BLUE}"
    cat << "EOF"
╔═══════════════════════════════════════════════════════════════╗
║                                                               ║
║   MERCURY QMS - API INTEGRATION TEST SUITE                   ║
║   Server: 138.68.65.104 (quality.mercurysurgelati.org)      ║
║                                                               ║
╚═══════════════════════════════════════════════════════════════╝
EOF
    echo -e "${NC}"
    
    # Check dependencies
    if ! command -v jq &> /dev/null; then
        print_error "jq is required but not installed. Install with: apt install jq"
        exit 1
    fi
    
    # Run tests based on scenario
    case "$scenario" in
        all)
            test_auth || echo "⚠️  Continuing without authentication"
            test_slots
            test_qms
            test_synthia
            test_fleetfix
            ;;
        auth)
            test_auth
            ;;
        synthia)
            test_auth || echo "⚠️  Continuing without authentication"
            test_synthia
            ;;
        qms)
            test_auth || echo "⚠️  Continuing without authentication"
            test_qms
            ;;
        slots)
            test_slots
            ;;
        fleetfix)
            test_auth || echo "⚠️  Continuing without authentication"
            test_fleetfix
            ;;
        audit)
            test_auth || exit 1
            test_audit_scenario
            ;;
        perf)
            test_performance
            ;;
        *)
            print_error "Unknown scenario: $scenario"
            show_help
            exit 1
            ;;
    esac
    
    echo ""
    print_header "✅ TEST COMPLETE"
}

# Run main
main "$@"

