CREATE OR REPLACE FUNCTION pricequote.pick_last_price_from_hist(
    hist JSONB,
    v1ds TEXT
)
RETURNS JSONB AS $$
DECLARE
    dsq JSONB := (hist -> v1ds) -> 'dsq';
    dss JSONB := (hist -> v1ds) -> 'dss';
    mrq JSONB := hist -> 'mrq';
    mrs JSONB := hist -> 'mrs';
    result JSONB;
BEGIN
    IF dsq IS NOT NULL AND (dsq->>'price') IS NOT NULL AND (dsq->>'odate')::date > (CURRENT_DATE - INTERVAL '1 year') THEN
        result := dsq || jsonb_build_object('source', 'dsq');
    ELSIF dss IS NOT NULL AND (dss->>'price') IS NOT NULL AND (dss->>'odate')::date > (CURRENT_DATE - INTERVAL '1 year') THEN
        result := dss || jsonb_build_object('source', 'dss');
    ELSIF mrq IS NOT NULL AND (mrq->>'price') IS NOT NULL THEN
        result := mrq || jsonb_build_object('source', 'mrq');
    ELSIF mrs IS NOT NULL AND (mrs->>'price') IS NOT NULL THEN
        result := mrs || jsonb_build_object('source', 'mrs');
    ELSE
        result := NULL;
    END IF;
    RETURN result;
END;
$$ LANGUAGE plpgsql IMMUTABLE;
