SET ANSI_NULLS ON;
GO
SET QUOTED_IDENTIFIER ON;
GO

CREATE OR ALTER PROCEDURE dbo.WordCompanion_Chapter_List
    @BookID int,
    @UserID int
AS
BEGIN
    SET NOCOUNT ON;

    IF NOT EXISTS
    (
        SELECT 1
        FROM dbo.Books b
        INNER JOIN dbo.Projects p ON p.ProjectID = b.ProjectID
        INNER JOIN dbo.ProjectUserAccess pua ON pua.ProjectID = p.ProjectID
        WHERE b.BookID = @BookID
            AND b.IsArchived = 0
            AND p.IsArchived = 0
            AND pua.UserID = @UserID
            AND pua.IsActive = 1
    )
        RETURN;

    SELECT c.ChapterID AS ChapterId,
        c.ChapterTitle AS Title,
        c.SortOrder
    FROM dbo.Chapters c
    WHERE c.BookID = @BookID
        AND c.IsArchived = 0
    ORDER BY c.SortOrder, c.ChapterNumber, c.ChapterID;
END;
GO

CREATE OR ALTER PROCEDURE dbo.WordCompanion_Chapter_Create
    @BookID int,
    @UserID int,
    @Title nvarchar(200),
    @SortOrder int = NULL
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @TrimmedTitle nvarchar(200) = LTRIM(RTRIM(COALESCE(@Title, N'')));
    IF NULLIF(@TrimmedTitle, N'') IS NULL OR @SortOrder <= 0
        RETURN;

    IF NOT EXISTS
    (
        SELECT 1
        FROM dbo.Books b
        INNER JOIN dbo.Projects p ON p.ProjectID = b.ProjectID
        INNER JOIN dbo.ProjectUserAccess pua ON pua.ProjectID = p.ProjectID
        WHERE b.BookID = @BookID
            AND b.IsArchived = 0
            AND p.IsArchived = 0
            AND pua.UserID = @UserID
            AND pua.IsActive = 1
    )
        RETURN;

    DECLARE @PlannedRevisionStatusID int = (SELECT TOP (1) RevisionStatusID FROM dbo.RevisionStatuses WHERE StatusName = N'Planned' ORDER BY SortOrder);
    IF @PlannedRevisionStatusID IS NULL
        RETURN;

    DECLARE @NextChapterNumber decimal(9,2) = ISNULL((SELECT MAX(ChapterNumber) FROM dbo.Chapters WHERE BookID = @BookID), 0) + 1;
    DECLARE @NextChapterOrder int = ISNULL((SELECT MAX(SortOrder) FROM dbo.Chapters WHERE BookID = @BookID), 0) + 10;
    DECLARE @ChapterID int;

    INSERT dbo.Chapters (BookID, ChapterNumber, ChapterTitle, Summary, SortOrder, RevisionStatusID)
    VALUES (@BookID, @NextChapterNumber, @TrimmedTitle, NULL, COALESCE(@SortOrder, @NextChapterOrder), @PlannedRevisionStatusID);

    SET @ChapterID = CAST(SCOPE_IDENTITY() AS int);

    SELECT @ChapterID AS ChapterId,
        @TrimmedTitle AS Title,
        COALESCE(@SortOrder, @NextChapterOrder) AS SortOrder,
        N'Chapter created successfully.' AS Message;
END;
GO
