-- ============================================================================
-- RAG 公共知识库未归属默认项迁移前检查
--
-- 用途：
--   检查历史 tenant_code 为空，area 为空/default/公共，且 is_public=true 的 RAG 知识库/应用。
--   这些记录在页面显示为“未分配地区”，且如果 is_default=true，会导致无法删除。
--
-- 执行：
--   psql -h <host> -U <user> -d <db_name> -v ON_ERROR_STOP=1 \
--     -f scripts/创建sql/precheck_rag_public_orphan_defaults.sql
-- ============================================================================

-- 1. 历史未归属公共知识库迁移候选
SELECT
    d.id,
    d.name,
    d.description,
    d.area,
    d.tenant_code,
    d.is_public,
    d.is_default,
    d.status,
    d.created_at,
    d.updated_at
FROM public.rag_dataset d
WHERE d.deleted_at IS NULL
  AND (d.tenant_code IS NULL OR BTRIM(d.tenant_code) = '')
  AND d.is_public IS TRUE
  AND (
      d.area IS NULL
      OR BTRIM(d.area) = ''
      OR LOWER(BTRIM(d.area)) = 'default'
      OR BTRIM(d.area) = '公共'
  )
ORDER BY d.is_default DESC, d.created_at DESC, d.id DESC;

-- 2. 当前 PUBLIC 组默认知识库
SELECT
    d.id,
    d.name,
    d.description,
    d.area,
    d.tenant_code,
    d.is_public,
    d.is_default,
    d.status,
    d.created_at,
    d.updated_at
FROM public.rag_dataset d
WHERE d.deleted_at IS NULL
  AND BTRIM(COALESCE(d.tenant_code, '')) = 'PUBLIC'
ORDER BY d.is_default DESC, d.created_at DESC, d.id DESC;

-- 3. 迁移后 PUBLIC 组默认冲突预览
WITH candidate AS (
    SELECT
        d.id,
        d.name,
        d.area,
        CASE
            WHEN BTRIM(COALESCE(d.tenant_code, '')) = 'PUBLIC' THEN 'existing_public'
            ELSE 'orphan_public'
        END AS source_scope,
        COALESCE(NULLIF(BTRIM(d.tenant_code), ''), 'PUBLIC') AS target_tenant_code,
        d.is_default,
        d.is_public,
        d.created_at
    FROM public.rag_dataset d
    WHERE d.deleted_at IS NULL
      AND (
          BTRIM(COALESCE(d.tenant_code, '')) = 'PUBLIC'
          OR (
              (d.tenant_code IS NULL OR BTRIM(d.tenant_code) = '')
              AND d.is_public IS TRUE
              AND (
                  d.area IS NULL
                  OR BTRIM(d.area) = ''
                  OR LOWER(BTRIM(d.area)) = 'default'
                  OR BTRIM(d.area) = '公共'
              )
          )
      )
),
ranked AS (
    SELECT
        c.*,
        ROW_NUMBER() OVER (
            PARTITION BY c.target_tenant_code
            ORDER BY
                c.is_default DESC,
                CASE WHEN c.source_scope = 'existing_public' THEN 0 ELSE 1 END,
                c.created_at DESC,
                c.id DESC
        ) AS keep_default_rank
    FROM candidate c
)
SELECT
    target_tenant_code,
    id,
    name,
    area,
    source_scope,
    is_public,
    is_default AS current_is_default,
    keep_default_rank,
    CASE WHEN keep_default_rank = 1 THEN '迁移后保留默认' ELSE '迁移后取消默认' END AS planned_default_action
FROM ranked
ORDER BY target_tenant_code, keep_default_rank, id;

-- 4. 关联应用候选
SELECT
    a.id,
    a.name,
    a.area,
    a.tenant_code,
    a.dataset_id,
    a.is_default,
    a.status,
    a.created_at,
    a.updated_at
FROM public.rag_chat_app a
JOIN public.rag_dataset d ON d.id = a.dataset_id
WHERE a.deleted_at IS NULL
  AND d.deleted_at IS NULL
  AND (a.tenant_code IS NULL OR BTRIM(a.tenant_code) = '')
  AND (d.tenant_code IS NULL OR BTRIM(d.tenant_code) = '')
  AND d.is_public IS TRUE
  AND (
      d.area IS NULL
      OR BTRIM(d.area) = ''
      OR LOWER(BTRIM(d.area)) = 'default'
      OR BTRIM(d.area) = '公共'
  )
ORDER BY a.is_default DESC, a.created_at DESC, a.id DESC;
