CREATE DATABASE prd_pointer;
\c prd_pointer

CREATE EXTENSION postgres_fdw;

CREATE SERVER dwh_prd
FOREIGN DATA WRAPPER postgres_fdw
OPTIONS (host '$PRD_HOST', dbname '$PRD_DB', port '$PRD_PORT');

ALTER SERVER dwh_prd OPTIONS (fetch_size '100000');

CREATE USER MAPPING FOR current_user
SERVER dwh_prd
OPTIONS (user '$PRD_CI_USER', password '$PRD_CI_PASSWORD');

CREATE OR REPLACE FUNCTION refresh_foreign_schemas(schema_list TEXT[]) RETURNS void AS $$
DECLARE
    schema_name TEXT;
BEGIN
    -- Loop through each schema in the provided list
    FOREACH schema_name IN ARRAY schema_list LOOP

        -- Drop and recreate the schema to avoid conflicts
        EXECUTE format('DROP SCHEMA IF EXISTS %I CASCADE', schema_name);
        EXECUTE format('CREATE SCHEMA %I', schema_name);

        -- Import all tables from the foreign server
        EXECUTE format(
            'IMPORT FOREIGN SCHEMA %I FROM SERVER dwh_prd INTO %I',
            schema_name, schema_name
        );

    END LOOP;
END;
$$ LANGUAGE plpgsql;
