#!/bin/bash

# Cloudflare Pages 部署模块
# 提供 Cloudflare Pages 部署功能

# 部署到 Cloudflare Pages 的函数
deploy_to_cloudflare() {
    local cloudflare_project_name="$1"
    local build_branch="$2"
    local dist_dir="${3:-dist}"

    # 验证凭证是否存在（不记录敏感值）
    if [ -z "${CLOUDFLARE_API_TOKEN}" ]; then
        log_message "❌ 错误: CLOUDFLARE_API_TOKEN 未设置"
        return 1
    fi

    log_message "✅ Cloudflare 凭证验证通过"

    log_message "========================================="
    log_message "开始部署到 Cloudflare Pages"
    log_message "========================================="
    log_message "项目名称: ${cloudflare_project_name}"
    log_message "构建目录: ${dist_dir}"
    log_message "分支: ${build_branch}"

    # 检查构建目录是否存在
    if [ ! -d "${dist_dir}" ]; then
        log_message "❌ 错误: 构建目录 ${dist_dir} 不存在"
        log_message "当前目录内容:"
        ls -la
        return 1
    fi

    log_message "✅ 构建目录检查通过"
    log_message "构建产物大小: $(du -sh ${dist_dir} | cut -f1)"
    log_message "文件数量: $(find ${dist_dir} -type f | wc -l)"

    # 部署到 Cloudflare Pages
    log_message "🚀 开始部署到 Cloudflare Pages..."
    DEPLOY_START=$(date +%s)

    # 使用 wrangler pages deploy 命令 (推荐方式)
    # --project-name: Pages 项目名称
    # --branch: 部署分支，用于预览环境
    # --commit-dirty: 允许未提交的更改

    # 执行部署命令并捕获输出和退出状态
    set +e # 临时禁用错误退出
    npx wrangler@3.99.0 pages deploy ${dist_dir} \
        --project-name="${cloudflare_project_name}" \
        --branch="${build_branch}" \
        --commit-dirty=true \
        2>&1 | tee -a "$BUILD_LOG_FILE"
    DEPLOY_EXIT_CODE=${PIPESTATUS[0]}
    set -e # 重新启用错误退出

    DEPLOY_END=$(date +%s)
    DEPLOY_DURATION=$((DEPLOY_END - DEPLOY_START))

    # 检查部署是否成功
    if [ ${DEPLOY_EXIT_CODE} -eq 0 ]; then
        log_message "========================================="
        log_message "✅ Cloudflare Pages 部署成功!"
        log_message "========================================="
        log_message "部署耗时: ${DEPLOY_DURATION}秒"

        # 根据分支判断访问地址
        if [ "${build_branch}" = "main" ] || [ "${build_branch}" = "master" ]; then
            log_message "📡 生产环境地址: https://${cloudflare_project_name}.pages.dev"
        else
            log_message "📡 预览环境地址: https://${build_branch}.${cloudflare_project_name}.pages.dev"
        fi

        return 0
    else
        log_message "========================================="
        log_message "❌ Cloudflare Pages 部署失败 (退出码: ${DEPLOY_EXIT_CODE})"
        log_message "========================================="
        log_message "部署耗时: ${DEPLOY_DURATION}秒"
        log_message ""
        log_message "请检查以下事项:"
        log_message "1. Cloudflare API Token 是否有效且具有 Pages 编辑权限"
        log_message "2. Cloudflare Account ID 是否正确"
        log_message "3. Pages 项目 '${cloudflare_project_name}' 是否已在 Dashboard 中创建"
        log_message "4. 访问 https://dash.cloudflare.com/profile/api-tokens 检查 Token 权限"
        log_message ""
        log_message "如果项目不存在，请先在 Cloudflare Dashboard 创建:"
        log_message "   Workers & Pages → Create → Pages → 项目名: ${cloudflare_project_name}"

        return 1
    fi
}
