CREATE OR REPLACE FUNCTION pricequote.guidance_logic(
    _target       numeric(20,5),
    _last_norm    numeric(20,5),
    _list_eff     numeric(20,5),
    _last_date    date,
    _floor_pct    numeric(10,5) DEFAULT 0.95,
    _cap_last_pct numeric(10,5) DEFAULT 1.00,
    _cap_list_pct numeric(10,5) DEFAULT 1.00
)
RETURNS TABLE (
    guidance_price numeric(20,5), 
    guidance_reason text
)
LANGUAGE plpgsql AS $$
DECLARE
    base_price     numeric(20,5);
    after_floor    numeric(20,5);
    after_cap_last numeric(20,5);
    final_price    numeric(20,5);
    reason         text := '';

BEGIN

    -- Early exit if nothing to work with
    IF _target IS NULL AND _last_norm IS NULL AND _list_eff IS NULL THEN
        RETURN QUERY SELECT NULL::numeric, 'No target, last, or list available';
        RETURN;
    END IF;

    
    -- Pick starting base price
    base_price := COALESCE(_target, _last_norm, _list_eff);
    -- Reason text
    reason := 
      CASE 
        WHEN _target IS NOT NULL THEN 'Using target price'
        WHEN _last_norm IS NOT NULL THEN 'Using last price as base'
        WHEN _list_eff IS NOT NULL THEN 'Using list price as base'
      END;

    -- Step 1: use base price less than last price, use last price
    IF base_price < _last_norm THEN 
        base_price := _last_norm;
        reason := 'Last price';
    END IF;

    -- Step 2: use price from previous step but don't allow it to be x% above last price
    IF base_price > _list_eff THEN 
        base_price := _list_eff;
        reason := 'List price ceiling';
    END IF;

    final_price := base_price;

    RETURN QUERY SELECT final_price, reason;
END $$;
