#!/bin/bash

# 推送指定分支到指定远端
# 期望服务器端 post-receive hook 已就位；本脚本只做 git push，不负责构建/启动
# 调用方：deploy_web.sh（production）→ push_to_remote "production" "main"
#        deploy_web_test.sh（test）→ push_to_remote "test" "test"
push_to_remote() {
    local remote="$1"
    local branch="$2"

    if [ -z "$remote" ] || [ -z "$branch" ]; then
        echo "错误: 未指定 remote 或 branch"
        return 1
    fi

    echo "=========================================="
    echo "git push $remote $branch ..."
    echo "=========================================="

    local current=$(git branch --show-current 2>/dev/null || echo "unknown")
    if [ "$current" != "$branch" ]; then
        echo "警告: 当前本地分支 = $current，目标分支 = $branch（不一致）"
    fi

    # 检查 remote 是否存在
    if ! git remote get-url "$remote" >/dev/null 2>&1; then
        echo "错误: git remote '$remote' 未配置"
        echo "  请运行: git remote add $remote <URL>"
        return 1
    fi

    git push "$remote" "$branch"

    if [ $? -eq 0 ]; then
        echo "=========================================="
        echo "推送成功！"
        echo "=========================================="
    else
        echo "=========================================="
        echo "推送失败！"
        echo "=========================================="
        return 1
    fi
    return 0
}

# 读取当前版本号（package.json）
get_version() {
    grep '"version":' package.json | head -1 | sed -E 's/.*"version":\s*"([^"]+)".*/\1/'
}

# 递增 build number 并更新 package.json
# 返回新的版本号（仅 stdout 输出版本号，日志输出到 stderr）
bump_version() {
    local current=$(get_version)

    if [ -z "$current" ]; then
        echo "错误: 无法读取当前版本号" >&2
        return 1
    fi

    # 解析版本号（格式: x.y.z+build）
    local build_num=$(echo "$current" | cut -d'+' -f2)
    local new_build_num=$((build_num + 1))
    local new_version="${current%%+*}+${new_build_num}"

    # 日志输出到 stderr
    echo "==========================================" >&2
    echo "更新版本号..." >&2
    echo "当前版本: $current" >&2
    echo "新版本: $new_version" >&2
    echo "==========================================" >&2

    # 更新 package.json（JSON 格式）
    sed -i.bak "s/\"version\":\s*\"$current\"/\"version\": \"$new_version\"/" package.json
    rm -f package.json.bak

    if [ $? -eq 0 ]; then
        echo "版本号更新成功: $new_version" >&2
    else
        echo "版本号更新失败！" >&2
        return 1
    fi

    # 只输出版本号到 stdout
    echo "$new_version"
}

# 清除 Cloudflare CDN 缓存
# 凭据从 .env.local 读（CF_ZONE_ID / CF_API_TOKEN）
purge_cdn_cache() {
    # 从 .env.local 读 CDN 凭据（Next.js 不读取，bash 直接 source）
    if [ -f .env.local ]; then
        # shell 解析 KEY=VALUE（忽略注释 / 引号）
        set -a
        # shellcheck disable=SC1091
        source .env.local 2>/dev/null || true
        set +a
    fi

    if [ -z "$CF_ZONE_ID" ] || [ -z "$CF_API_TOKEN" ]; then
        echo "错误: Cloudflare 配置不完整（CF_ZONE_ID / CF_API_TOKEN），跳过缓存清除"
        return 1
    fi

    echo "=========================================="
    echo "开始清除 Cloudflare CDN 缓存..."
    echo "Zone ID: $CF_ZONE_ID"
    echo "=========================================="

    local response=$(curl -s -X POST "https://api.cloudflare.com/client/v4/zones/$CF_ZONE_ID/purge_cache" \
        -H "Authorization: Bearer $CF_API_TOKEN" \
        -H "Content-Type: application/json" \
        -d '{"purge_everything":true}')

    if echo "$response" | grep -q '"success":true'; then
        echo "=========================================="
        echo "CDN 缓存清除成功！"
        echo "=========================================="
        return 0
    else
        echo "=========================================="
        echo "CDN 缓存清除失败！"
        echo "响应: $response"
        echo "=========================================="
        return 1
    fi
}
