-- ============================================================================
-- Rule Domain Tenant Phase 1 Precheck
-- 目标：
--   1. 执行前确认规则域现状
--   2. 识别历史全局规则资产规模
--   3. 识别运行结果快照回填影响范围
-- ============================================================================

-- 1. 核心表是否存在
SELECT table_name
FROM information_schema.tables
WHERE table_schema = current_schema()
  AND table_name IN (
    'leaudit_rule_sets',
    'leaudit_rule_versions',
    'leaudit_rule_group_bindings',
    'leaudit_rule_type_bindings',
    'leaudit_audit_runs',
    'leaudit_rule_results',
    'leaudit_run_errors',
    'leaudit_run_metrics'
  )
ORDER BY table_name;

-- 2. 当前列缺失情况
SELECT
    table_name,
    column_name
FROM information_schema.columns
WHERE table_schema = current_schema()
  AND table_name IN (
    'leaudit_rule_sets',
    'leaudit_rule_versions',
    'leaudit_rule_group_bindings',
    'leaudit_rule_type_bindings',
    'leaudit_audit_runs',
    'leaudit_rule_results',
    'leaudit_run_errors',
    'leaudit_run_metrics'
  )
  AND column_name IN (
    'tenant_code',
    'scope_type',
    'tenant_code_snapshot',
    'scope_type_snapshot',
    'source_rule_set_id',
    'source_version_id',
    'tenant_name_snapshot',
    'group_id_snapshot',
    'rule_binding_id_snapshot'
  )
ORDER BY table_name, column_name;

-- 3. 规则集与规则版本规模
SELECT 'leaudit_rule_sets' AS table_name, COUNT(*) AS total
FROM leaudit_rule_sets
WHERE deleted_at IS NULL
UNION ALL
SELECT 'leaudit_rule_versions' AS table_name, COUNT(*) AS total
FROM leaudit_rule_versions
UNION ALL
SELECT 'leaudit_rule_group_bindings' AS table_name, COUNT(*) AS total
FROM leaudit_rule_group_bindings
WHERE deleted_at IS NULL;

-- 4. 历史全局规则资产规模
SELECT
    COUNT(*) AS global_rule_sets_without_tenant_code
FROM leaudit_rule_sets
WHERE deleted_at IS NULL
  AND (
    tenant_code IS NULL
    OR BTRIM(tenant_code) = ''
  );

SELECT
    COUNT(*) AS global_group_bindings_without_tenant_code
FROM leaudit_rule_group_bindings
WHERE deleted_at IS NULL
  AND (
    tenant_code IS NULL
    OR BTRIM(tenant_code) = ''
  );

-- 5. 运行主表与结果表快照缺口
SELECT
    COUNT(*) AS audit_runs_missing_tenant_code
FROM leaudit_audit_runs
WHERE tenant_code IS NULL
   OR BTRIM(tenant_code) = '';

SELECT
    COUNT(*) AS rule_results_missing_tenant_code
FROM leaudit_rule_results
WHERE tenant_code IS NULL
   OR BTRIM(tenant_code) = '';

SELECT
    COUNT(*) AS run_errors_missing_tenant_code
FROM leaudit_run_errors
WHERE tenant_code IS NULL
   OR BTRIM(tenant_code) = '';

SELECT
    COUNT(*) AS run_metrics_missing_tenant_code
FROM leaudit_run_metrics
WHERE tenant_code IS NULL
   OR BTRIM(tenant_code) = '';

-- 6. 文档租户缺口，会直接影响 audit_runs 回填质量
SELECT
    COUNT(*) AS documents_missing_tenant_code
FROM leaudit_documents
WHERE deleted_at IS NULL
  AND (
    tenant_code IS NULL
    OR BTRIM(tenant_code) = ''
  );
