do $$
begin
    if to_regclass('public.crm_sales_expansion') is null then
        raise notice 'table crm_sales_expansion does not exist, skip';
        return;
    end if;

    if exists (
        select 1
        from information_schema.columns
        where table_schema = 'public'
          and table_name = 'crm_sales_expansion'
          and column_name = 'target_dept_id'
    ) then
        if not exists (
            select 1
            from information_schema.columns
            where table_schema = 'public'
              and table_name = 'crm_sales_expansion'
              and column_name = 'target_dept'
        ) then
            alter table crm_sales_expansion add column target_dept varchar(100);
        end if;

        update crm_sales_expansion s
        set target_dept = coalesce(
            nullif(s.target_dept, ''),
            (
                select d.item_label
                from sys_dict_item d
                where d.type_code = 'tz_ssbm'
                  and d.item_value = s.target_dept_id::varchar
                  and d.status = 1
                  and coalesce(d.is_deleted, 0) = 0
                order by d.sort_order asc nulls last, d.dict_item_id asc
                limit 1
            ),
            (
                select o.org_name
                from sys_org o
                where o.id = s.target_dept_id
                limit 1
            ),
            s.target_dept_id::varchar
        )
        where s.target_dept_id is not null;

        alter table crm_sales_expansion drop column target_dept_id;
    elsif exists (
        select 1
        from information_schema.columns
        where table_schema = 'public'
          and table_name = 'crm_sales_expansion'
          and column_name = 'target_dept'
    ) then
        alter table crm_sales_expansion
            alter column target_dept type varchar(100);
    end if;
end $$;
