-- CREATE OR ALTER FUNCTION pricing.guidance_logic;

CREATE OR ALTER FUNCTION pricing.guidance_logic(
    @target       numeric(20,5),
    @last_norm    numeric(20,5),
    @list_eff     numeric(20,5),
    @last_date    date,
    @floor_pct    numeric(10,5) = 0.95,
    @cap_last_pct numeric(10,5) = 1.00,
    @cap_list_pct numeric(10,5) = 1.00
)
RETURNS @ret TABLE (
    guidance_price  numeric(20,5),
    guidance_reason nvarchar(4000)
)
AS
BEGIN
    DECLARE
        @base_price     numeric(20,5),  -- starting point (target if available, else last_norm, else list_eff)
        @after_floor    numeric(20,5),  -- base but limited to x% lower than last price
        @after_cap_last numeric(20,5),  -- previous step but limited to x% higher than last price
        @final_price    numeric(20,5),  -- previous step but limited to x% higher than list price
        @reason         nvarchar(4000) = N'';  -- logic source of price

    -- Early exit if nothing to work with
    IF @target IS NULL AND @last_norm IS NULL AND @list_eff IS NULL
    BEGIN
        INSERT INTO @ret VALUES (NULL, N'No target, last, or list available');
        RETURN;
    END;

    -- Early exit if only list price is available
    IF @target IS NULL AND @last_norm IS NULL 
    BEGIN
        INSERT INTO @ret VALUES (NULL, N'Only List price is available, disregard');
        RETURN;
    END;

    -- Pick starting base price
    SET @base_price = COALESCE(@target, @last_norm, @list_eff);
    -- Reason text
    SET @reason = 
      CASE 
        WHEN @target IS NOT NULL THEN N'Using target price'
        WHEN @last_norm IS NOT NULL THEN N'Using last price as base'
        WHEN @list_eff IS NOT NULL THEN N'Using list price as base'
      END;

    -- Step 1: use base price less than last price, use last price
    IF @base_price < @last_norm
    BEGIN
    	SET @base_price = @last_norm;
    	SET @reason = N'Last price';
    END
    	

    -- Step 2: use price from previous step but don't allow it to be x% above last price
    IF @base_price > @list_eff
    BEGIN
    	SET @base_price = @list_eff;
    	SET @reason = N'List price ceiling';
    END
    
    SET @final_price = @base_price;
                       
    INSERT INTO @ret VALUES (@final_price, @reason);
    RETURN;
END;
