#!/bin/bash

# ISO 27001 資產盤點系統 - 快速測試腳本
# 用於驗證系統功能是否正常運作

echo "========================================="
echo " ISO 27001 資產盤點系統 - 功能測試"
echo "========================================="
echo ""

# 顏色定義
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 測試後端健康狀態
test_backend() {
    echo -n "測試後端服務... "
    response=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:8000/api/assets/)
    if [ "$response" = "200" ]; then
        echo -e "${GREEN}✓ 通過${NC}"
        return 0
    else
        echo -e "${RED}✗ 失敗 (HTTP $response)${NC}"
        return 1
    fi
}

# 測試前端服務
test_frontend() {
    echo -n "測試前端服務... "
    response=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:3000/)
    if [ "$response" = "200" ] || [ "$response" = "304" ]; then
        echo -e "${GREEN}✓ 通過${NC}"
        return 0
    else
        echo -e "${RED}✗ 失敗 (HTTP $response)${NC}"
        return 1
    fi
}

# 測試資料庫連接
test_database() {
    echo -n "測試資料庫連接... "
    result=$(docker compose exec -T db psql -U iso27001_user -d iso27001_db -c "SELECT 1;" 2>&1)
    if echo "$result" | grep -q "1 row"; then
        echo -e "${GREEN}✓ 通過${NC}"
        return 0
    else
        echo -e "${RED}✗ 失敗${NC}"
        return 1
    fi
}

# 測試 API 認證
test_auth() {
    echo -n "測試 API 認證... "
    response=$(curl -s -X POST http://localhost:8000/api/auth/login/ \
        -H "Content-Type: application/json" \
        -d '{"username":"admin","password":"admin123"}')
    
    if echo "$response" | grep -q "access_token"; then
        echo -e "${GREEN}✓ 通過${NC}"
        # 儲存 token 供後續測試使用
        echo "$response" | grep -o '"access_token":"[^"]*"' | sed 's/"access_token":"//' | sed 's/"//' > /tmp/test_token.txt
        return 0
    else
        echo -e "${RED}✗ 失敗${NC}"
        return 1
    fi
}

# 測試資產列表 API
test_asset_list() {
    echo -n "測試資產列表 API... "
    response=$(curl -s http://localhost:8000/api/assets/)
    
    if echo "$response" | grep -q "count"; then
        count=$(echo "$response" | grep -o '"count":[0-9]*' | sed 's/"count"://')
        echo -e "${GREEN}✓ 通過 (共 $count 筆資產)${NC}"
        return 0
    else
        echo -e "${RED}✗ 失敗${NC}"
        return 1
    fi
}

# 測試資產統計 API
test_asset_statistics() {
    echo -n "測試資產統計 API... "
    response=$(curl -s http://localhost:8000/api/assets/statistics/)
    
    if echo "$response" | grep -q "total"; then
        echo -e "${GREEN}✓ 通過${NC}"
        return 0
    else
        echo -e "${RED}✗ 失敗${NC}"
        return 1
    fi
}

# 測試新增資產 API
test_create_asset() {
    echo -n "測試新增資產 API... "
    
    # 產生隨機編號
    random_num=$((RANDOM % 10000))
    asset_number="TEST-$random_num"
    
    response=$(curl -s -X POST http://localhost:8000/api/assets/ \
        -H "Content-Type: application/json" \
        -d "{
            \"asset_number\": \"$asset_number\",
            \"name\": \"測試資產-$random_num\",
            \"asset_type\": \"hardware\",
            \"status\": \"active\",
            \"confidentiality\": \"medium\",
            \"integrity\": \"medium\",
            \"availability\": \"medium\"
        }")
    
    if echo "$response" | grep -q "$asset_number"; then
        echo -e "${GREEN}✓ 通過${NC}"
        # 儲存資產 ID 供清理使用
        asset_id=$(echo "$response" | grep -o '"id":"[^"]*"' | head -1 | sed 's/"id":"//' | sed 's/"//')
        echo "$asset_id" > /tmp/test_asset_id.txt
        return 0
    else
        echo -e "${RED}✗ 失敗${NC}"
        return 1
    fi
}

# 清理測試資產
cleanup_test_asset() {
    if [ -f /tmp/test_asset_id.txt ]; then
        asset_id=$(cat /tmp/test_asset_id.txt)
        echo -n "清理測試資產... "
        curl -s -X DELETE "http://localhost:8000/api/assets/$asset_id/" > /dev/null
        echo -e "${GREEN}✓ 完成${NC}"
        rm /tmp/test_asset_id.txt
    fi
}

# 顯示系統資訊
show_system_info() {
    echo ""
    echo "========================================="
    echo " 系統資訊"
    echo "========================================="
    echo "後端 URL:  http://localhost:8000"
    echo "前端 URL:  http://localhost:3000"
    echo "API 文件:  http://localhost:8000/api/schema/swagger-ui/"
    echo ""
    echo "預設帳號:"
    echo "  使用者名稱: admin"
    echo "  密碼:       admin123"
    echo ""
}

# 主測試流程
main() {
    # 檢查服務是否啟動
    echo "========================================="
    echo " 服務狀態檢查"
    echo "========================================="
    test_backend || exit 1
    test_frontend || echo -e "${YELLOW}⚠ 前端可能尚未啟動或正在編譯${NC}"
    test_database || exit 1
    
    echo ""
    echo "========================================="
    echo " API 功能測試"
    echo "========================================="
    test_auth || exit 1
    test_asset_list || exit 1
    test_asset_statistics || exit 1
    test_create_asset || exit 1
    
    echo ""
    echo "========================================="
    echo " 清理測試資料"
    echo "========================================="
    cleanup_test_asset
    
    # 顯示系統資訊
    show_system_info
    
    echo "========================================="
    echo -e " ${GREEN}所有測試完成！${NC}"
    echo "========================================="
}

# 執行主程式
main
