#!/bin/bash
# Flower Database Access - 远程访问示例脚本
# 通过SSH连接到远程服务器执行数据库查询

set -e

# SSH连接参数
SSH_HOST="8.148.215.233"
SSH_PORT="18762"
SSH_USER="root"

# 数据库连接参数（在远程服务器上）
DB_HOST="127.0.0.1"
DB_PORT="5432"
DB_NAME="flower"
DB_USER="postgres"
DB_PASS="postgres"

# SSH命令前缀
SSH_CMD="ssh -p $SSH_PORT $SSH_USER@$SSH_HOST"

# 数据库查询命令
function db_query() {
    $SSH_CMD "PGPASSWORD=$DB_PASS psql -h $DB_HOST -p $DB_PORT -U $DB_USER -d $DB_NAME -c \"$1\""
}

echo "=== Flower ERP 数据库远程访问示例 ==="
echo "远程服务器: $SSH_HOST:$SSH_PORT"
echo

# 测试SSH连接
echo "=== 测试SSH连接 ==="
echo "---"
if $SSH_CMD "echo 'SSH连接成功'" &> /dev/null; then
    echo "✓ SSH连接正常"
else
    echo "✗ SSH连接失败，请检查SSH key配置"
    exit 1
fi
echo

# 示例1: 查询商户信息
echo "1. 查询商户列表:"
echo "---"
db_query "
SELECT id, name, type, created_at 
FROM basic_info_merchant 
ORDER BY created_at DESC 
LIMIT 5;
"
echo

# 示例2: 查询最近的销售订单
echo "2. 查询最近10条销售订单:"
echo "---"
db_query "
SELECT 
    so.id,
    so.sales_date,
    c.name as customer_name,
    so.status,
    so.created_at
FROM business_salesorder so
JOIN basic_info_customer c ON so.customer_id = c.id
ORDER BY so.created_at DESC
LIMIT 10;
"
echo

# 示例3: 查询库存
echo "3. 查询库存状态（前10个）:"
echo "---"
db_query "
SELECT 
    p.name as product_name,
    w.name as warehouse,
    si.quantity,
    p.unit
FROM stock_inventory si
JOIN basic_info_product p ON si.product_id = p.id
JOIN basic_info_warehouse w ON si.warehouse_id = w.id
WHERE si.quantity > 0
ORDER BY si.quantity DESC
LIMIT 10;
"
echo

# 示例4: 查询印染订单统计
echo "4. 印染订单统计（最近7天）:"
echo "---"
db_query "
SELECT 
    DATE(created_at) as date,
    COUNT(*) as total_orders,
    SUM(CASE WHEN is_urgent THEN 1 ELSE 0 END) as urgent_orders,
    SUM(CASE WHEN is_fabric_received THEN 1 ELSE 0 END) as fabric_received
FROM printing_printingorder
WHERE created_at >= CURRENT_DATE - INTERVAL '7 days'
GROUP BY DATE(created_at)
ORDER BY date DESC;
"
echo

# 示例5: 查询开版订单进度
echo "5. 开版订单进度统计:"
echo "---"
db_query "
SELECT 
    po.id,
    po.style_name,
    po.plate_type,
    po.urgency_level,
    po.is_ordered,
    po.created_at
FROM printing_plateorder po
WHERE po.is_invalid = false
ORDER BY po.created_at DESC
LIMIT 10;
"
echo

# 示例6: 查询最大的表
echo "6. 数据库表大小统计（前10）:"
echo "---"
db_query "
SELECT 
    schemaname,
    tablename,
    pg_size_pretty(pg_total_relation_size(schemaname||'.'||tablename)) as size
FROM pg_tables
WHERE schemaname = 'public'
ORDER BY pg_total_relation_size(schemaname||'.'||tablename) DESC
LIMIT 10;
"
echo

# 示例7: 使用SSH隧道
echo "7. SSH隧道方式（可选）:"
echo "---"
echo "如果需要本地访问，可以创建SSH隧道："
echo "  ssh -p $SSH_PORT -L 15432:127.0.0.1:5432 $SSH_USER@$SSH_HOST -N"
echo "  然后在另一个终端："
echo "  PGPASSWORD=$DB_PASS psql -h 127.0.0.1 -p 15432 -U $DB_USER -d $DB_NAME"
echo

echo "=== 示例完成 ==="
echo "更多查询示例请查看 SKILL.md 文件"
echo
echo "💡 提示："
echo "   - 所有查询都是只读的"
echo "   - 不要访问 auth_* 认证表"
echo "   - 查询时考虑 merchant_id（多租户）"
