BEGIN;

-- ============================================================================
-- Evaluation Points Tenant Cleanup
-- 目标：
--   1. 为旧表 evaluation_points 补 tenant_code / tenant_name
--   2. 建立基础索引，支持评查点模块彻底切到 tenant_code 主链
--   3. 基于 sys_tenant_aliases / sys_tenants 做首轮历史回填
-- 说明：
--   - 当前真实运行链路仍使用旧表 evaluation_points
--   - 本脚本只做“补列 + 建索引 + 回填”
--   - 不在本阶段删除旧 area 字段
--   - 不在本阶段强制 NOT NULL
-- ============================================================================

-- --------------------------------------------------------------------------
-- 1. 补字段
-- --------------------------------------------------------------------------
ALTER TABLE public.evaluation_points
    ADD COLUMN IF NOT EXISTS tenant_code VARCHAR(64),
    ADD COLUMN IF NOT EXISTS tenant_name VARCHAR(128);

COMMENT ON COLUMN public.evaluation_points.tenant_code IS '所属租户编码：评查点历史收尾阶段新增，后续替代 area 作为真实归属主字段';
COMMENT ON COLUMN public.evaluation_points.tenant_name IS '所属租户名称：展示字段，和 tenant_code 配套回填';

-- --------------------------------------------------------------------------
-- 2. 基础索引
-- --------------------------------------------------------------------------
CREATE INDEX IF NOT EXISTS idx_evaluation_points_tenant_code
    ON public.evaluation_points(tenant_code);

CREATE INDEX IF NOT EXISTS idx_evaluation_points_group_tenant_code
    ON public.evaluation_points(evaluation_point_groups_id, tenant_code);

CREATE INDEX IF NOT EXISTS idx_evaluation_points_group_pid_tenant_code
    ON public.evaluation_points(evaluation_point_groups_pid, tenant_code);

-- --------------------------------------------------------------------------
-- 3. 公共 / 省级规范租户兜底
-- --------------------------------------------------------------------------
INSERT INTO public.sys_tenants (
    tenant_code, tenant_name, tenant_short_name, tenant_type,
    parent_tenant_code, is_enabled, is_public, display_order, ext,
    created_at, updated_at, deleted_at
)
SELECT
    'PUBLIC', '公共资源域', '公共', 'PUBLIC',
    NULL, TRUE, TRUE, 0, '{}'::jsonb,
    NOW(), NOW(), NULL
WHERE NOT EXISTS (
    SELECT 1 FROM public.sys_tenants WHERE tenant_code = 'PUBLIC'
);

INSERT INTO public.sys_tenants (
    tenant_code, tenant_name, tenant_short_name, tenant_type,
    parent_tenant_code, is_enabled, is_public, display_order, ext,
    created_at, updated_at, deleted_at
)
SELECT
    'PROVINCIAL', '省级统管域', '省级', 'GOV',
    NULL, TRUE, FALSE, 1, '{}'::jsonb,
    NOW(), NOW(), NULL
WHERE NOT EXISTS (
    SELECT 1 FROM public.sys_tenants WHERE tenant_code = 'PROVINCIAL'
);

INSERT INTO public.sys_tenant_aliases (
    tenant_code, alias_type, alias_value, is_enabled, created_at, updated_at, deleted_at
)
SELECT 'PUBLIC', 'DISPLAY', '公共', TRUE, NOW(), NOW(), NULL
WHERE NOT EXISTS (
    SELECT 1
    FROM public.sys_tenant_aliases
    WHERE tenant_code = 'PUBLIC'
      AND alias_value = '公共'
      AND deleted_at IS NULL
);

INSERT INTO public.sys_tenant_aliases (
    tenant_code, alias_type, alias_value, is_enabled, created_at, updated_at, deleted_at
)
SELECT 'PUBLIC', 'LEGACY_REGION', 'default', TRUE, NOW(), NOW(), NULL
WHERE NOT EXISTS (
    SELECT 1
    FROM public.sys_tenant_aliases
    WHERE tenant_code = 'PUBLIC'
      AND alias_value = 'default'
      AND deleted_at IS NULL
);

INSERT INTO public.sys_tenant_aliases (
    tenant_code, alias_type, alias_value, is_enabled, created_at, updated_at, deleted_at
)
SELECT 'PROVINCIAL', 'DISPLAY', '省级', TRUE, NOW(), NOW(), NULL
WHERE NOT EXISTS (
    SELECT 1
    FROM public.sys_tenant_aliases
    WHERE tenant_code = 'PROVINCIAL'
      AND alias_value = '省级'
      AND deleted_at IS NULL
);

INSERT INTO public.sys_tenant_aliases (
    tenant_code, alias_type, alias_value, is_enabled, created_at, updated_at, deleted_at
)
SELECT 'PROVINCIAL', 'LEGACY_REGION', '省局', TRUE, NOW(), NOW(), NULL
WHERE NOT EXISTS (
    SELECT 1
    FROM public.sys_tenant_aliases
    WHERE tenant_code = 'PROVINCIAL'
      AND alias_value = '省局'
      AND deleted_at IS NULL
);

-- --------------------------------------------------------------------------
-- 4. 历史回填：优先按别名表映射
-- --------------------------------------------------------------------------
WITH alias_map AS (
    SELECT DISTINCT ON (LOWER(BTRIM(alias_value)))
        LOWER(BTRIM(alias_value)) AS normalized_alias_value,
        tenant_code
    FROM public.sys_tenant_aliases
    WHERE deleted_at IS NULL
      AND is_enabled = TRUE
    ORDER BY LOWER(BTRIM(alias_value)), id ASC
),
tenant_name_map AS (
    SELECT
        LOWER(BTRIM(tenant_name)) AS normalized_tenant_name,
        tenant_code
    FROM public.sys_tenants
    WHERE deleted_at IS NULL
      AND is_enabled = TRUE
),
resolved_points AS (
    SELECT
        ep.id,
        COALESCE(
            NULLIF(BTRIM(ep.tenant_code), ''),
            am.tenant_code,
            tn.tenant_code,
            CASE
                WHEN ep.area IS NULL OR BTRIM(ep.area) = '' THEN 'PUBLIC'
                WHEN LOWER(BTRIM(ep.area)) = 'default' THEN 'PUBLIC'
                WHEN BTRIM(ep.area) = '公共' THEN 'PUBLIC'
                WHEN BTRIM(ep.area) IN ('省级', '省局') THEN 'PROVINCIAL'
                ELSE NULL
            END
        ) AS resolved_tenant_code,
        COALESCE(
            NULLIF(BTRIM(ep.tenant_name), ''),
            st.tenant_name,
            NULLIF(BTRIM(ep.area), ''),
            CASE
                WHEN ep.area IS NULL OR BTRIM(ep.area) = '' THEN '公共资源域'
                WHEN LOWER(BTRIM(ep.area)) = 'default' THEN '公共资源域'
                WHEN BTRIM(ep.area) = '公共' THEN '公共资源域'
                WHEN BTRIM(ep.area) IN ('省级', '省局') THEN '省级统管域'
                ELSE NULL
            END
        ) AS resolved_tenant_name
    FROM public.evaluation_points ep
    LEFT JOIN alias_map am
      ON LOWER(BTRIM(COALESCE(ep.area, ''))) = am.normalized_alias_value
    LEFT JOIN tenant_name_map tn
      ON LOWER(BTRIM(COALESCE(ep.area, ''))) = tn.normalized_tenant_name
    LEFT JOIN public.sys_tenants st
      ON st.tenant_code = COALESCE(
          NULLIF(BTRIM(ep.tenant_code), ''),
          am.tenant_code,
          tn.tenant_code,
          CASE
              WHEN ep.area IS NULL OR BTRIM(ep.area) = '' THEN 'PUBLIC'
              WHEN LOWER(BTRIM(ep.area)) = 'default' THEN 'PUBLIC'
              WHEN BTRIM(ep.area) = '公共' THEN 'PUBLIC'
              WHEN BTRIM(ep.area) IN ('省级', '省局') THEN 'PROVINCIAL'
              ELSE NULL
          END
      )
     AND st.deleted_at IS NULL
     AND st.is_enabled = TRUE
    WHERE
        ep.tenant_code IS NULL
        OR BTRIM(ep.tenant_code) = ''
        OR ep.tenant_name IS NULL
        OR BTRIM(ep.tenant_name) = ''
)
UPDATE public.evaluation_points ep
SET tenant_code = COALESCE(NULLIF(BTRIM(ep.tenant_code), ''), rp.resolved_tenant_code),
    tenant_name = COALESCE(NULLIF(BTRIM(ep.tenant_name), ''), rp.resolved_tenant_name)
FROM resolved_points rp
WHERE ep.id = rp.id
  AND (
      rp.resolved_tenant_code IS NOT NULL
      OR rp.resolved_tenant_name IS NOT NULL
  );

COMMIT;
