SET ANSI_NULLS ON;
GO
SET QUOTED_IDENTIFIER ON;
GO

CREATE OR ALTER PROCEDURE dbo.Scene_SavePurposes
    @SceneID int,
    @PurposeIds nvarchar(max)
AS
BEGIN
    SET NOCOUNT ON;

    DELETE FROM dbo.ScenePurposes WHERE SceneID = @SceneID;

    INSERT dbo.ScenePurposes (SceneID, ScenePurposeTypeID)
    SELECT DISTINCT @SceneID, parsed.ScenePurposeTypeID
    FROM
    (
        SELECT TRY_CAST(value AS int) AS ScenePurposeTypeID
        FROM STRING_SPLIT(ISNULL(@PurposeIds, N''), N',')
    ) parsed
    INNER JOIN dbo.ScenePurposeTypes spt ON spt.ScenePurposeTypeID = parsed.ScenePurposeTypeID
    WHERE parsed.ScenePurposeTypeID IS NOT NULL
        AND parsed.ScenePurposeTypeID > 0
        AND spt.IsArchived = 0;
END;
GO
