#!/bin/bash

set -euo pipefail

# 从环境变量获取测试域名（deploy.sh 传入）
DOMAIN="${TEST_DOMAIN:-https://xmclassmate.top}"

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

log_info() { echo -e "${GREEN}[INFO]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }

check_health() {
    local url="${1}/health"
    log_info "检查健康端点: ${url}"

    local status_code
    status_code=$(curl -s -o /dev/null -w "%{http_code}" --max-time 10 "${url}" 2>/dev/null || echo "000")

    if [ "$status_code" = "200" ]; then
        log_info "健康检查通过 (HTTP $status_code)"
        return 0
    else
        log_error "健康检查失败 (HTTP $status_code)"
        return 1
    fi
}

check_api() {
    local url="${1}"
    log_info "检查 API 端点: ${url}"

    local status_code
    status_code=$(curl -s -o /dev/null -w "%{http_code}" --max-time 10 -k \
        -H "Host: xmclassmate.top" \
        "${url}" 2>/dev/null || echo "000")

    if [ "$status_code" = "200" ] || [ "$status_code" = "401" ] || [ "$status_code" = "301" ] || [ "$status_code" = "302" ]; then
        log_info "API 端点正常 (HTTP $status_code)"
        return 0
    else
        log_error "API 端点异常 (HTTP $status_code)"
        return 1
    fi
}

check_static_files() {
    local static_files=(
        "/static/katex/katex.min.css"
        "/static/css/style.css"
        "/static/favicon.ico"
    )

    log_info "检查静态文件..."

    local failed=0
    for file in "${static_files[@]}"; do
        local status_code
        status_code=$(curl -s -o /dev/null -w "%{http_code}" --max-time 10 -k \
            -H "Host: xmclassmate.top" \
            "${DOMAIN}${file}" 2>/dev/null || echo "000")

        if [ "$status_code" = "200" ]; then
            log_info "静态文件 ${file} 正常"
        else
            log_error "静态文件 ${file} 异常 (HTTP $status_code)"
            failed=1
        fi
    done

    return $failed
}

main() {
    local failed=0

    echo ""
    echo -e "${YELLOW}========== 部署后测试 ==========${NC}"
    echo -e "  测试域名: ${DOMAIN}"
    echo -e "================================${NC}"
    echo ""

    if ! check_health "${DOMAIN}"; then
        failed=1
    fi

    if ! check_api "${DOMAIN}"; then
        failed=1
    fi

    if ! check_static_files; then
        failed=1
    fi

    echo ""
    if [ $failed -eq 0 ]; then
        log_info "========== 所有测试通过 =========="
        exit 0
    else
        log_error "========== 部分测试失败 =========="
        exit 1
    fi
}

main "$@"
