USE [FirstSolutionDB]
GO

-- ============================================================
-- SP: cedlab_Chart_UnderlyingOnly
-- Restituisce lo storico prezzi di UN SOLO sottostante, senza
-- alcun contesto certificato (nessuno strike/barriera/trigger).
-- Usata da UnderlyingChartDataService per il grafico standalone
-- sottostante.
--
-- Output (Px_date ASC, TOP 350 più recenti):
--   Nome     VARCHAR  -- "{Name} ({Ticker_bbg})", uguale su ogni riga
--   Px_date  DATE
--   Px       DECIMAL  -- Px_close o Px_closeadj in base ad AdjustedPrices
-- ============================================================

CREATE OR ALTER PROCEDURE [dbo].[cedlab_Chart_UnderlyingOnly]
    @IDUnderlyings INT
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @AdjustedPrices BIT;
    SELECT @AdjustedPrices = ISNULL(AdjustedPrices, 0)
    FROM dbo.Underlyings
    WHERE IDUnderlyings = @IDUnderlyings
      AND deleted = 0
      AND sospeso = 0;

    IF @AdjustedPrices IS NULL RETURN; -- non trovato / cancellato / sospeso

    ;WITH Ranked AS
    (
        SELECT
            p.Px_date,
            CASE WHEN @AdjustedPrices = 0 THEN p.Px_close ELSE p.Px_closeadj END AS Px,
            ROW_NUMBER() OVER (ORDER BY p.Px_date DESC) AS rn
        FROM dbo.Prices p
        WHERE p.UnderlyingsID = @IDUnderlyings
          AND (p.Px_low IS NOT NULL OR p.Px_high IS NOT NULL OR
               p.Px_open IS NOT NULL OR p.Px_close IS NOT NULL)
    )
    SELECT
        CONCAT(u.Name, ' (', u.Ticker_bbg, ')') AS Nome,
        r.Px_date,
        r.Px
    FROM Ranked r
    CROSS JOIN (SELECT TOP 1 * FROM dbo.Underlyings WHERE IDUnderlyings = @IDUnderlyings) u
    WHERE r.rn <= 350
    ORDER BY r.Px_date ASC;
END
GO
