USE [FirstSolutionDB]
GO

-- ============================================================
-- SP: cedlab_Chart_AllSeriesV2
-- Restituisce tutte le serie (CTF + tutti UL) in un unico round-trip.
-- Usata da ChartDataServiceV2 per il grafico V2.
--
-- Logica basata su:
--   - cedlab_Chart_DailyUL1: stessa formula performance UL, stessi filtri
--   - cedlab_Chart_UL1: Strike da CertificatesUnderlyings, StartDate = MIN(Prices.Px_date)
--
-- Output (IDUnderlyings ASC, Px_date ASC):
--   IDUnderlyings  INT      -- 0 = CTF, altrimenti UnderlyingsID
--   Px_date        DATE
--   Performance    DECIMAL  -- % su strike/nominal
-- ============================================================

CREATE OR ALTER PROCEDURE [dbo].[cedlab_Chart_AllSeriesV2]
    @isin VARCHAR(15)
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @IDCertificates INT;
    DECLARE @Nominal        DECIMAL(18, 6);
    DECLARE @StartDate      DATE;

    SELECT TOP 1
        @IDCertificates = c.IDCertificates,
        @Nominal        = c.Nominal_amount
    FROM dbo.Certificates c
    WHERE c.ISIN = @isin;

    IF @IDCertificates IS NULL RETURN;

    -- StartDate = prima data di prezzi EOD del certificato
    -- (identica a cedlab_Chart_UL1: MIN(p.Px_date) con join su Prices)
    SELECT @StartDate = MIN(p.Px_date)
    FROM dbo.Prices p
    WHERE p.CertificatesID = @IDCertificates;

    -- ── CTE: TOP 350 per-serie tramite ROW_NUMBER DESC, poi reinverte ASC ──
    WITH AllSeriesRaw AS
    (
        -- ── Serie CTF (IDUnderlyings = 0) ────────────────────────────────
        -- Performance = PX_LAST_EOD / Nominal_amount * 100
        SELECT
            0                                  AS IDUnderlyings,
            pc.Px_date,
            CONVERT(DECIMAL(18, 4),
                pc.PX_LAST_EOD / NULLIF(@Nominal, 0) * 100
            )                                  AS Performance,
            ROW_NUMBER() OVER (
                PARTITION BY 0
                ORDER BY pc.Px_date DESC
            )                                  AS rn
        FROM dbo.Prices pc
        WHERE pc.CertificatesID = @IDCertificates
          AND pc.PX_LAST_EOD IS NOT NULL
          AND pc.PX_LAST_EOD <> 0

        UNION ALL

        -- ── Serie UL (tutti i sottostanti del certificato) ────────────────
        -- Identica a cedlab_Chart_DailyUL1 per ogni UL attivo.
        -- Strike da CertificatesUnderlyings (come in cedlab_Chart_UL1).
        -- Date allineate al CTF (INNER JOIN su Prices per CertificatesID).
        SELECT
            pu.UnderlyingsID                   AS IDUnderlyings,
            pu.Px_date,
            CONVERT(DECIMAL(18, 4),
                CASE
                    WHEN ISNULL(u.AdjustedPrices, 0) = 0 THEN pu.Px_close
                    ELSE pu.Px_closeadj
                END
                / NULLIF(cu.Strike, 0) * 100
            )                                  AS Performance,
            ROW_NUMBER() OVER (
                PARTITION BY pu.UnderlyingsID
                ORDER BY pu.Px_date DESC
            )                                  AS rn
        FROM dbo.Prices pu
        LEFT JOIN dbo.Underlyings u
            ON u.IDUnderlyings = pu.UnderlyingsID
        INNER JOIN dbo.CertificatesUnderlyings cu
            ON cu.UnderlyingsID  = pu.UnderlyingsID
           AND cu.CertificatesID = @IDCertificates
        -- Allinea date UL al CTF (solo date con prezzo CTF valido)
        INNER JOIN dbo.Prices pc
            ON pu.Px_date        = pc.Px_date
           AND pc.CertificatesID = @IDCertificates
           AND pc.PX_LAST_EOD   IS NOT NULL
           AND pc.PX_LAST_EOD   <> 0
        WHERE cu.deleted  = 0
          AND u.deleted   = 0
          AND u.sospeso   = 0
          AND (
                pu.px_low   IS NOT NULL OR pu.Px_high  IS NOT NULL OR
                pu.Px_open  IS NOT NULL OR pu.Px_close IS NOT NULL
              )
          AND pu.px_date >= @StartDate
    )

    SELECT
        IDUnderlyings,
        Px_date,
        Performance
    FROM AllSeriesRaw
    WHERE rn <= 350
    ORDER BY IDUnderlyings ASC, Px_date ASC;

END
GO
