#!/bin/bash

# 微信配置验证脚本
# 用途：检查微信公众号和支付配置的完整性

set -e

echo "========================================"
echo "  微信配置验证脚本"
echo "========================================"
echo ""

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

# 错误计数
ERROR_COUNT=0
WARNING_COUNT=0

# 检查环境变量是否存在
check_env() {
    local var_name=$1
    local is_required=${2:-true}
    
    if [ -z "${!var_name}" ]; then
        if [ "$is_required" = true ]; then
            echo -e "${RED}✗ 缺失必填配置: $var_name${NC}"
            ((ERROR_COUNT++))
            return 1
        else
            echo -e "${YELLOW}⚠ 缺失可选配置: $var_name${NC}"
            ((WARNING_COUNT++))
            return 0
        fi
    else
        echo -e "${GREEN}✓ $var_name${NC}"
        return 0
    fi
}

# 检查文件是否存在
check_file() {
    local file_path=$1
    local var_name=$2
    
    if [ ! -f "$file_path" ]; then
        echo -e "${RED}✗ 文件不存在: $file_path (来自 $var_name)${NC}"
        ((ERROR_COUNT++))
        return 1
    else
        echo -e "${GREEN}✓ 文件存在: $file_path${NC}"
        
        # 检查文件权限
        local perms=$(stat -f "%A" "$file_path" 2>/dev/null || stat -c "%a" "$file_path" 2>/dev/null)
        if [ "$perms" != "600" ] && [ "$perms" != "644" ] && [ "$perms" != "400" ]; then
            echo -e "${YELLOW}  ⚠ 建议修改文件权限为 600: chmod 600 $file_path${NC}"
            ((WARNING_COUNT++))
        fi
        return 0
    fi
}

# 检查字符串长度
check_length() {
    local var_name=$1
    local expected_length=$2
    local value="${!var_name}"
    
    if [ ${#value} -ne $expected_length ]; then
        echo -e "${YELLOW}  ⚠ $var_name 长度应为 $expected_length 位，当前 ${#value} 位${NC}"
        ((WARNING_COUNT++))
        return 1
    fi
    return 0
}

echo "1. 检查微信公众号配置"
echo "----------------------------------------"
check_env "JUNHONG_WECHAT_OFFICIAL_ACCOUNT_APP_ID" true
check_env "JUNHONG_WECHAT_OFFICIAL_ACCOUNT_APP_SECRET" true
check_env "JUNHONG_WECHAT_OFFICIAL_ACCOUNT_TOKEN" false
check_env "JUNHONG_WECHAT_OFFICIAL_ACCOUNT_AES_KEY" false
check_env "JUNHONG_WECHAT_OFFICIAL_ACCOUNT_OAUTH_REDIRECT_URL" false
echo ""

echo "2. 检查微信支付配置"
echo "----------------------------------------"
check_env "JUNHONG_WECHAT_PAYMENT_APP_ID" true
check_env "JUNHONG_WECHAT_PAYMENT_MCH_ID" true
check_env "JUNHONG_WECHAT_PAYMENT_API_V3_KEY" true
check_env "JUNHONG_WECHAT_PAYMENT_API_V2_KEY" false
check_env "JUNHONG_WECHAT_PAYMENT_CERT_PATH" true
check_env "JUNHONG_WECHAT_PAYMENT_KEY_PATH" true
check_env "JUNHONG_WECHAT_PAYMENT_SERIAL_NO" true
check_env "JUNHONG_WECHAT_PAYMENT_NOTIFY_URL" true
check_env "JUNHONG_WECHAT_PAYMENT_HTTP_DEBUG" false
check_env "JUNHONG_WECHAT_PAYMENT_TIMEOUT" false
echo ""

echo "3. 检查证书文件"
echo "----------------------------------------"
if [ -n "$JUNHONG_WECHAT_PAYMENT_CERT_PATH" ]; then
    check_file "$JUNHONG_WECHAT_PAYMENT_CERT_PATH" "JUNHONG_WECHAT_PAYMENT_CERT_PATH"
fi

if [ -n "$JUNHONG_WECHAT_PAYMENT_KEY_PATH" ]; then
    check_file "$JUNHONG_WECHAT_PAYMENT_KEY_PATH" "JUNHONG_WECHAT_PAYMENT_KEY_PATH"
fi
echo ""

echo "4. 验证配置格式"
echo "----------------------------------------"

# 检查 AppID 格式（应以 wx 开头）
if [ -n "$JUNHONG_WECHAT_OFFICIAL_ACCOUNT_APP_ID" ]; then
    if [[ ! "$JUNHONG_WECHAT_OFFICIAL_ACCOUNT_APP_ID" =~ ^wx ]]; then
        echo -e "${YELLOW}  ⚠ 公众号 AppID 格式可能有误（通常以 wx 开头）${NC}"
        ((WARNING_COUNT++))
    fi
fi

# 检查 APIv3 密钥长度（应为 32 位）
if [ -n "$JUNHONG_WECHAT_PAYMENT_API_V3_KEY" ]; then
    check_length "JUNHONG_WECHAT_PAYMENT_API_V3_KEY" 32
fi

# 检查回调 URL 格式（必须是 HTTPS）
if [ -n "$JUNHONG_WECHAT_PAYMENT_NOTIFY_URL" ]; then
    if [[ ! "$JUNHONG_WECHAT_PAYMENT_NOTIFY_URL" =~ ^https:// ]]; then
        echo -e "${RED}✗ 支付回调 URL 必须使用 HTTPS${NC}"
        ((ERROR_COUNT++))
    else
        echo -e "${GREEN}✓ 支付回调 URL 使用 HTTPS${NC}"
    fi
fi
echo ""

echo "5. 检查证书有效性（可选）"
echo "----------------------------------------"
if [ -n "$JUNHONG_WECHAT_PAYMENT_CERT_PATH" ] && [ -f "$JUNHONG_WECHAT_PAYMENT_CERT_PATH" ]; then
    if command -v openssl &> /dev/null; then
        # 检查证书是否过期
        expiry_date=$(openssl x509 -in "$JUNHONG_WECHAT_PAYMENT_CERT_PATH" -noout -enddate 2>/dev/null | cut -d= -f2)
        if [ -n "$expiry_date" ]; then
            echo -e "${GREEN}✓ 证书有效期至: $expiry_date${NC}"
            
            # 检查证书序列号是否匹配
            cert_serial=$(openssl x509 -in "$JUNHONG_WECHAT_PAYMENT_CERT_PATH" -noout -serial 2>/dev/null | cut -d= -f2)
            if [ -n "$cert_serial" ]; then
                if [ "$cert_serial" != "$JUNHONG_WECHAT_PAYMENT_SERIAL_NO" ]; then
                    echo -e "${YELLOW}  ⚠ 证书序列号不匹配${NC}"
                    echo -e "    配置中: $JUNHONG_WECHAT_PAYMENT_SERIAL_NO"
                    echo -e "    证书中: $cert_serial"
                    ((WARNING_COUNT++))
                else
                    echo -e "${GREEN}  ✓ 证书序列号匹配${NC}"
                fi
            fi
        fi
    else
        echo -e "${YELLOW}  ⚠ 未安装 openssl，跳过证书验证${NC}"
    fi
fi
echo ""

echo "========================================"
echo "  验证结果"
echo "========================================"
echo -e "${RED}错误: $ERROR_COUNT${NC}"
echo -e "${YELLOW}警告: $WARNING_COUNT${NC}"
echo ""

if [ $ERROR_COUNT -gt 0 ]; then
    echo -e "${RED}❌ 配置验证失败，请修复上述错误后重试${NC}"
    echo ""
    echo "建议操作："
    echo "1. 检查 .env.local 文件是否正确加载"
    echo "2. 确认所有必填环境变量已设置"
    echo "3. 验证证书文件路径是否正确"
    echo "4. 参考文档: docs/wechat-integration/使用指南.md"
    exit 1
elif [ $WARNING_COUNT -gt 0 ]; then
    echo -e "${YELLOW}⚠️  配置验证通过，但存在警告${NC}"
    echo ""
    echo "建议操作："
    echo "1. 检查警告信息并根据建议调整"
    echo "2. 警告不会影响服务启动，但可能影响功能"
    exit 0
else
    echo -e "${GREEN}✅ 配置验证通过，所有配置正确${NC}"
    echo ""
    echo "下一步："
    echo "1. 启动服务: go run cmd/api/main.go"
    echo "2. 查看启动日志确认微信服务初始化成功"
    echo "3. 参考验证指南进行功能测试: docs/wechat-integration/验证指南.md"
    exit 0
fi
