#!/bin/bash
# ===========================================
# 通过 SSH 在服务器上执行 SQL，使用户的付费时间过期
# 仅修改 membership_expires_at 到过去日期
# is_member 保持 true，is_active_member 会变为 false
# ===========================================

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"
CONFIG_DIR="$PROJECT_ROOT/config"
ENV_FILE="$PROJECT_ROOT/.env"

get_ssh_host() {
    grep '^SSH_SERVER=' "$ENV_FILE" 2>/dev/null | head -1 | cut -d'=' -f2- | tr -d '"' | tr -d "'" | xargs
}

usage() {
    echo "用法: $0 <user_id> [--date YYYY-MM-DD]"
    echo ""
    echo "  user_id          用户 ID（必填）"
    echo "  --date YYYY-MM-DD  指定到期日期（默认：昨天，即立即过期）"
    echo ""
    echo "示例:"
    echo "  $0 1                   # 用户 1 立即过期"
    echo "  $0 1 --date 2025-01-01 # 用户 1 在 2025-01-01 过期"
    exit 0
}

# ---------- 参数解析 ----------
USER_ID=""
EXPIRES_DATE=""

while [[ $# -gt 0 ]]; do
    case "$1" in
        --date) EXPIRES_DATE="$2"; shift 2 ;;
        --dev) DB_NAME="milkydata_dev"; shift ;;
        --help|-h) usage ;;
        *) USER_ID="$1"; shift ;;
    esac
done

[ -z "$USER_ID" ] && usage

# ---------- 连接信息 ----------
SSH_HOST=$(get_ssh_host)
[ -z "$SSH_HOST" ] && { echo "错误: 未配置 SSH_SERVER"; exit 1; }

DB_CONTAINER="1Panel-postgresql-FtMo"
DB_USER="milkydata"

# ---------- 设置过期日期 ----------
if [ -z "$EXPIRES_DATE" ]; then
    EXPIRES_DATE=$(date -d "yesterday" +%Y-%m-%d)
    echo "未指定日期，默认设为昨天: ${EXPIRES_DATE}"
fi

echo "═══════════════════════════════════════"
echo "用户 ${USER_ID} 会员过期操作"
echo "到期日期: ${EXPIRES_DATE}"
echo "═══════════════════════════════════════"

echo ""

echo "⚠️  即将执行以下操作："
echo "  将用户 ${USER_ID} 的 membership_expires_at 设到 ${EXPIRES_DATE}"
echo "  is_member 保持 true（用户仍标记为曾付费）"
echo "  用户的 is_active_member 会变为 false（付费已过期）"
echo ""
read -p "确认执行? [y/N] " -n 1 -r; echo
[[ ! $REPLY =~ ^[Yy]$ ]] && { echo "已取消"; exit 0; }

# ---------- 执行 SQL ----------
SQL="UPDATE users SET is_member = true, membership_expires_at = '${EXPIRES_DATE}'::date WHERE id = ${USER_ID};"

echo "执行 SQL: ${SQL}"
ssh "$SSH_HOST" "docker exec ${DB_CONTAINER} psql -U ${DB_USER} -d ${DB_NAME} -c \"${SQL}\"" && echo "✅ 操作成功" || echo "❌ 操作失败"

# 查询验证
QUERY_SQL="SELECT id, name, phone, type, is_member, is_admin, membership_expires_at FROM users WHERE id = ${USER_ID};"
echo ""
echo "验证结果："
ssh "$SSH_HOST" "docker exec ${DB_CONTAINER} psql -U ${DB_USER} -d ${DB_NAME} -c \"${QUERY_SQL}\""

echo ""
echo "提示: is_member 保持 true，is_active_member 会变为 false（付费已过期）"
