#!/usr/bin/env bash
# check-permissions.sh — 权限注册完整性 CI 检查
#
# 检查三处权限定义的一致性：
#   1. 后端 handler 中的 require_permission 调用
#   2. 前端 routeConfig.ts 中的路由权限声明
#   3. 数据库迁移中的权限 seed 数据
#
# 用法: bash scripts/check-permissions.sh
# 返回: 0=通过, 1=发现不一致

set -uo pipefail
cd "$(git rev-parse --show-toplevel)"

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

# 临时文件
BACKEND_PERMS=$(mktemp)
FRONTEND_PERMS=$(mktemp)
SEED_PERMS=$(mktemp)
trap 'rm -f "$BACKEND_PERMS" "$FRONTEND_PERMS" "$SEED_PERMS"' EXIT

echo "=========================================="
echo "  权限注册完整性检查"
echo "=========================================="

# --- 提取后端 handler 权限码 ---
# 1) require_permission 调用
grep -roh 'require_permission.*"[^"]*"' crates/ --include="*.rs" \
  | grep -oE '"[^"]*"' | tr -d '"' | sort -u > "$BACKEND_PERMS"
# 2) module.rs 中 PermissionDescriptor 声明的 code 字段
grep -roh 'code: *"[^"]*"' crates/ --include="*.rs" \
  | grep -oE '"[^"]*\.[^"]*\.[^"]*"' | tr -d '"' | sort -u >> "$BACKEND_PERMS"
# 去重
cat "$BACKEND_PERMS" | sort -u > "${BACKEND_PERMS}.tmp" && mv "${BACKEND_PERMS}.tmp" "$BACKEND_PERMS"

# --- 提取前端 routeConfig 权限码 ---
grep -oE '"[a-z][-a-z0-9]*\.[a-z][-a-z0-9]*\.[a-z][-a-z0-9]*"' \
  apps/web/src/routeConfig.ts | tr -d '"' | sort -u > "$FRONTEND_PERMS"

# --- 提取 seed 迁移权限码 ---
# 匹配三段式（health.patient.list）和两段式（plugin.admin）权限码
grep -rohE '[a-z][-a-z0-9]*\.[a-z][-a-z0-9]*(\.[a-z][-a-z0-9]*)?' \
  crates/erp-server/migration/src/ --include="*.rs" \
  | grep -vE 'fn |mod |use |struct |impl |async |let |pub |self|super|crate' \
  | grep -E '^(user|role|workflow|message|setting|plugin|department|organization|position|dictionary|menu|numbering|theme|language|tenant|ai|copilot|health)' \
  | grep -v '\.(rs|sql|md|toml)$' \
  | sort -u > "$SEED_PERMS"
# 提取 handler 中的非 health 权限码也加入 seed 对比
grep -roh 'require_permission.*"[^"]*"' crates/erp-auth/ crates/erp-config/ crates/erp-workflow/ crates/erp-message/ --include="*.rs" \
  | grep -oE '"[^"]*"' | tr -d '"' | sort -u >> "$SEED_PERMS"
# 去重
cat "$SEED_PERMS" | sort -u > "${SEED_PERMS}.tmp" && mv "${SEED_PERMS}.tmp" "$SEED_PERMS"

echo ""
echo "统计: 后端 $(wc -l < "$BACKEND_PERMS") 个 | 前端 $(wc -l < "$FRONTEND_PERMS") 个 | Seed $(wc -l < "$SEED_PERMS") 个"
echo ""

ERRORS=0

# --- 检查 1: 前端引用了但后端不存在的权限码 ---
echo "--- 检查 1: 前端权限码是否在后端 handler 中存在 ---"
while IFS= read -r perm; do
  if ! grep -q "^${perm}$" "$BACKEND_PERMS"; then
    echo -e "  ${RED}MISSING${NC} 前端声明 '$perm' 但后端 handler 未使用"
    ERRORS=$((ERRORS + 1))
  fi
done < "$FRONTEND_PERMS"

if [ $ERRORS -eq 0 ]; then
  echo -e "  ${GREEN}OK${NC} 前端所有权限码在后端都有对应"
fi

echo ""

# --- 检查 2: 后端 handler 有但 seed 迁移缺失的权限码 ---
echo "--- 检查 2: 后端权限码是否在 seed 迁移中注册 ---"
SEED_MISSING=0
while IFS= read -r perm; do
  if ! grep -q "^${perm}$" "$SEED_PERMS"; then
    echo -e "  ${RED}MISSING${NC} 后端使用 '$perm' 但 seed 迁移未注册"
    SEED_MISSING=$((SEED_MISSING + 1))
    ERRORS=$((ERRORS + 1))
  fi
done < "$BACKEND_PERMS"

if [ $SEED_MISSING -eq 0 ]; then
  echo -e "  ${GREEN}OK${NC} 后端所有权限码在 seed 中都已注册"
fi

echo ""

# --- 检查 3: 每个 .list 权限是否配有 .manage ---
echo "--- 检查 3: 每个实体是否同时有 .list 和 .manage ---"
LIST_PERMS=$(grep -E '\.list$' "$BACKEND_PERMS" || true)
while IFS= read -r list_perm; do
  [ -z "$list_perm" ] && continue
  manage_perm="${list_perm%.list}.manage"
  if ! grep -q "^${manage_perm}$" "$BACKEND_PERMS"; then
    echo -e "  ${YELLOW}WARN${NC} '$list_perm' 缺少对应的 '$manage_perm'"
  fi
done <<< "$LIST_PERMS"

echo ""

# --- 总结 ---
echo "=========================================="
if [ $ERRORS -gt 0 ]; then
  echo -e "  ${RED}FAIL${NC} 发现 $ERRORS 个不一致"
  exit 1
else
  echo -e "  ${GREEN}PASS${NC} 权限注册完整性检查通过"
  exit 0
fi
