SET ANSI_NULLS ON;
GO
SET QUOTED_IDENTIFIER ON;
GO

CREATE OR ALTER PROCEDURE dbo.WordCompanion_Runtime_CurrentScene_Validate
    @UserID int,
    @DocumentGuid uniqueidentifier,
    @ProjectID int,
    @BookID int,
    @ChapterID int,
    @SceneID int
AS
BEGIN
    SET NOCOUNT ON;

    IF @DocumentGuid IS NULL
        OR @DocumentGuid = '00000000-0000-0000-0000-000000000000'
        OR @ProjectID <= 0
        OR @BookID <= 0
        OR @ChapterID <= 0
        OR @SceneID <= 0
        RETURN;

    SELECT p.ProjectID AS ProjectId,
        b.BookID AS BookId,
        c.ChapterID AS ChapterId,
        s.SceneID AS SceneId,
        CONCAT(N'/Scenes/Edit/', s.SceneID) AS SceneUrl
    FROM dbo.Projects p
    INNER JOIN dbo.ProjectUserAccess pua ON pua.ProjectID = p.ProjectID
    INNER JOIN dbo.Books b ON b.ProjectID = p.ProjectID
    INNER JOIN dbo.Chapters c ON c.BookID = b.BookID
    INNER JOIN dbo.Scenes s ON s.ChapterID = c.ChapterID
    INNER JOIN dbo.ManuscriptDocuments md ON md.ProjectID = p.ProjectID
        AND md.BookID = b.BookID
    WHERE p.ProjectID = @ProjectID
        AND b.BookID = @BookID
        AND c.ChapterID = @ChapterID
        AND s.SceneID = @SceneID
        AND md.DocumentGuid = @DocumentGuid
        AND md.IsActive = 1
        AND s.IsLinkedToManuscript = 1
        AND s.ManuscriptDocumentID = md.ManuscriptDocumentID
        AND p.IsArchived = 0
        AND b.IsArchived = 0
        AND c.IsArchived = 0
        AND s.IsArchived = 0
        AND pua.UserID = @UserID
        AND pua.IsActive = 1;
END;
GO
