CREATE OR REPLACE FUNCTION rlarp.gethist(_item text, _cust text)
RETURNS jsonb 
LANGUAGE plpgsql
AS $func$
DECLARE
    result jsonb;
BEGIN
    WITH getj AS (
        SELECT (
            SELECT jsonb_build_object('mold', JSON_AGG(DISTINCT stlc)) 
            FROM "CMS.CUSLG".itemm 
            WHERE item ~ _item
        ) || (
            SELECT jsonb_build_object('cust', JSONB_AGG(DISTINCT c.dba))
            FROM rlarp.cust c
            WHERE c.dba ~ _cust
        ) AS doc
    ),
    agg AS (
        SELECT 
            gset,
            (SELECT string_agg(ae.v, '.') FROM jsonb_array_elements_text(p.agglevel) ae(v)) AS agglvl,
            season,
            (SELECT doc FROM getj) AS gdoc
        FROM rlarp.price_pool_dev p
        WHERE  
            gset @> jsonb_build_object(
                'mold', (SELECT doc->'mold'->>0 FROM getj),
                'vers', 'A'
            )
            AND (
                gset @> jsonb_build_object(
                    'cust', (SELECT doc->'cust'->>0 FROM getj)
                )
                OR NOT gset ? 'cust'
            )
        ORDER BY agglevel ASC
    ),
    aggfinal AS (
        SELECT
            jsonb_build_object(
                agg.agglvl,
                jsonb_agg(gset || jsonb_build_object('season', season))
            ) AS data,
            gdoc
        FROM agg
        GROUP BY agglvl, gdoc
    ),
    final AS (
        SELECT 
            public.jsonb_obj_aggc(data) AS data,
            gdoc 
        FROM aggfinal 
        GROUP BY gdoc
    )
    SELECT data INTO result FROM final;

    RETURN result;

END
$func$;

