#!/bin/bash

# 推送指定分支到指定远端。
# 当前发布由 Gitea Actions 构建镜像并通过 SSH 部署；本脚本只负责触发分支 push。
# 调用方：deploy_web.sh（production）→ push_to_remote "gitea" "main"
#        deploy_web_test.sh（test）→ push_to_remote "gitea" "test"
push_to_remote() {
    local remote="$1"
    local branch="$2"

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

    local push_args=("--force")

    echo "=========================================="
    echo "git push ${push_args[*]-} $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

    if [ "${#push_args[@]}" -gt 0 ]; then
        git push "${push_args[@]}" "$remote" "$branch"
    else
        git push "$remote" "$branch"
    fi

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

source_env_file() {
    local file="$1"
    if [ ! -f "$file" ]; then
        return 1
    fi

    echo "读取环境变量文件: $file"
    set -a
    # shellcheck disable=SC1090
    source "$file" 2>/dev/null || true
    set +a
    return 0
}

# 清除 Cloudflare CDN 缓存
# 凭据按当前分支读取：
#   main → .env.production
#   其他 → .env.local
purge_cdn_cache() {
    local current=$(git branch --show-current 2>/dev/null || echo "unknown")
    local primary_env=".env.local"
    local fallback_env=".env.production"

    if [ "$current" = "main" ]; then
        primary_env=".env.production"
        fallback_env=".env.local"
    fi

    source_env_file "$primary_env" || true

    if [ -z "${CF_ZONE_ID:-}" ] || [ -z "${CF_API_TOKEN:-}" ]; then
        source_env_file "$fallback_env" || true
    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
}
