-- ============================================================
-- Скрипт приведения схемы eds_global (с проверкой существования)
-- PostgreSQL 16
-- ============================================================

DO $$
DECLARE
    v_obj_name text;
    v_obj_type text;
    v_sql text;
BEGIN
    RAISE NOTICE '=== Начало приведения схемы eds_global ===';

    -- Разрешенные таблицы
    CREATE TEMP TABLE IF NOT EXISTS allowed_tables AS
    SELECT unnest(ARRAY[
        'accountinggroupmodels',
        'acsdoctypemodels',
        'activitytypemodels',
        'agreementkindmodels',
        'aspersonaltypemodels',
        'authtypemodels',
        'BackgroundServiceStatusModel',
        'capabilitysettingsmodels',
        'casetypemodels',
        'constructionobjectmodels',
        'correspondentmodels',
        'currencymodels',
        'departmentmodels',
        'documentkindmodels',
        'EdsDigitalDocumentTemplateModel',
        'edsagreemententrymodels',
        'edsdoctypemodels',
        'EdsIntegrationSystemDictionaryModel',
        'EdsIntegrationSystemDocTypeModel',
        'EdsIntegrationSystemOstOptionsModel',
        'EdsIntegrationSystemStatusModel',
        'EdsLifecycleModel',
        'edsrepoinfos',
        'edsreturnreasonmodels',
        'edssubtypemodels',
        'EmployeeAttributesStorageModel',
        'employeemodels',
        'eventkindmodels',
        'eventreasonmodels',
        'fixedassetmodels',
        'M4DDictionaryModel',
        'packagelifecyclemodels',
        'PersonnelEmployeeModel',
        'RelationModel',
        'replacementtasklifecyclemodels',
        'reportmodels',
        'returnreasonmodels',
        'RoleInfoModel',
        'ScanStationAllowedRescanStatusModel',
        'ScanStationBatchTypeModel',
        'ScanStationConfidentialityModel',
        'ScanStationCountragentToRnuModel',
        'signaturealgorithmmodel',
        'SubmissionOverdueReasonModel',
        'SystemIntegrityControlItemModel',
        'SystemIntegrityControlModel',
        'SystemIntegrityControlStorageModel',
        'timelimitationmodels',
        'UserHelpModel',
        'uzdodoctypemodels',
        'withdrawtasklifecyclemodels',
        'workingdayscalendarmodels'
    ]) AS name;

    -- Разрешенные вьюхи
    CREATE TEMP TABLE IF NOT EXISTS allowed_views AS
    SELECT unnest(ARRAY[
        'UserHelpMap',
        'View_AnyDocumentKindMap',
        'View_ArchiveOrganizationMap',
        'View_EdsAgreementEntriesMap',
        'View_EdsDocumentKindMap',
        'View_EmployeePositionMap',
        'View_OrgStructureMap',
        'View_OrgStructureReportMap'
    ]) AS name;

    -- ============================================================
    -- Удаление лишних таблиц
    -- ============================================================
    RAISE NOTICE '--- Удаление лишних таблиц ---';

    FOR v_obj_name IN (
        SELECT tablename
        FROM pg_catalog.pg_tables
        WHERE schemaname = 'eds_global'
          AND tablename NOT IN (SELECT name FROM allowed_tables)
    ) LOOP
        EXECUTE format('DROP TABLE IF EXISTS eds_global.%I CASCADE;', v_obj_name);
        RAISE NOTICE '  Удалена таблица: %', v_obj_name;
    END LOOP;

    -- ============================================================
    -- Удаление лишних вьюх
    -- ============================================================
    RAISE NOTICE '--- Удаление лишних вьюх ---';

    FOR v_obj_name IN (
        SELECT viewname
        FROM pg_catalog.pg_views
        WHERE schemaname = 'eds_global'
          AND viewname NOT IN (SELECT name FROM allowed_views)
    ) LOOP
        EXECUTE format('DROP VIEW IF EXISTS eds_global.%I CASCADE;', v_obj_name);
        RAISE NOTICE '  Удалена вьюха: %', v_obj_name;
    END LOOP;

    -- ============================================================
    -- Очистка временных таблиц
    -- ============================================================
    DROP TABLE IF EXISTS allowed_tables;
    DROP TABLE IF EXISTS allowed_views;

    -- ============================================================
    -- Финальный отчет
    -- ============================================================
    RAISE NOTICE '=== ИТОГОВЫЙ СОСТАВ ===';
    
    RAISE NOTICE '--- Таблицы ---';
    FOR v_obj_name IN (
        SELECT tablename 
        FROM pg_catalog.pg_tables 
        WHERE schemaname = 'eds_global' 
        ORDER BY tablename
    ) LOOP
        RAISE NOTICE '  %', v_obj_name;
    END LOOP;

    RAISE NOTICE '--- Вьюхи ---';
    FOR v_obj_name IN (
        SELECT viewname 
        FROM pg_catalog.pg_views 
        WHERE schemaname = 'eds_global' 
        ORDER BY viewname
    ) LOOP
        RAISE NOTICE '  %', v_obj_name;
    END LOOP;

    RAISE NOTICE '=== ГОТОВО ===';
END $$;