DROP FUNCTION IF EXISTS rlarp.get_premium;
CREATE OR REPLACE FUNCTION rlarp.get_premium(_mold text, _season int, _chan text, _relevant text, _quoted text)
RETURNS jsonb 
LANGUAGE plpgsql AS
--DO
$func$
BEGIN

DECLARE
    _factor jsonb;

WITH
--targte spreads--
bridge AS (
    SELECT 
        -- 'FHR14000'     mold
        --,2024           season
        --,'DIRECT'       chan
        --,'v1:B..SLV..'  relevant
        --,'v1:S..SLV..'  quoted  
         _mold          mold
        ,_season        season
        ,_chan          chan
        ,_relevant      relevant
        ,_quoted        quoted  
)
,ts AS (
   SELECT 
        t.*
        --, round(target_price/min(target_price) over (partition by mold, chan, season),5) spread 
        ,t.target_price/min(t.target_price) over (partition by t.mold, t.chan, t.season) spread 
        ,b.quoted
        ,b.relevant
        ,CASE t.data_segment WHEN b.quoted THEN 'get to here' WHEN b.relevant THEN 'from here' END flag
    FROM
        pricequote.market_setavgprice t
        INNER JOIN bridge b ON
                t.mold =   b.mold
            and t.season = b.season
            and t.chan =   b.chan
            and t.data_segment like 'v1%' 
            and t.geo             = 'ALL'
            and t.country         = 'ALL'
            and t.geo             = 'ALL'
    ORDER BY 
        target_price ASC
)
--SELECT * FROM ts
SELECT 
    --mold
    --,chan
    --,season
    --,ROUND(max(spread) FILTER (WHERE flag = 'get to here'),5)  quote
    --,ROUND(max(spread) FILTER (WHERE flag = 'from here')  ,5)  relevant
    jsonb_build_object('bridgePremium',ROUND(max(spread) FILTER (WHERE flag = 'get to here')  
    /max(spread) FILTER (WHERE flag = 'from here')        ,5))
INTO
    _factor
FROM 
    ts 
GROUP BY 
    mold
    ,chan
    ,season;

RETURN _factor;
END
$func$
