SET ANSI_NULLS ON;
GO
SET QUOTED_IDENTIFIER ON;
GO

IF COL_LENGTH(N'dbo.Books', N'Subtitle') IS NULL
    ALTER TABLE dbo.Books ADD Subtitle nvarchar(200) NULL;
GO

IF COL_LENGTH(N'dbo.Books', N'Tagline') IS NULL
    ALTER TABLE dbo.Books ADD Tagline nvarchar(300) NULL;
GO

IF COL_LENGTH(N'dbo.Books', N'ShortDescription') IS NULL
    ALTER TABLE dbo.Books ADD ShortDescription nvarchar(max) NULL;
GO

IF COL_LENGTH(N'dbo.Books', N'Status') IS NULL
    ALTER TABLE dbo.Books ADD Status nvarchar(50) NOT NULL CONSTRAINT DF_Books_Status DEFAULT N'Planning';
GO

IF COL_LENGTH(N'dbo.Books', N'TargetWordCount') IS NULL
    ALTER TABLE dbo.Books ADD TargetWordCount int NULL;
GO

IF COL_LENGTH(N'dbo.Books', N'WritingStartDate') IS NULL
    ALTER TABLE dbo.Books ADD WritingStartDate date NULL;
GO

IF COL_LENGTH(N'dbo.Books', N'TargetCompletionDate') IS NULL
    ALTER TABLE dbo.Books ADD TargetCompletionDate date NULL;
GO

IF COL_LENGTH(N'dbo.Books', N'PublicationDate') IS NULL
    ALTER TABLE dbo.Books ADD PublicationDate date NULL;
GO

IF NOT EXISTS (SELECT 1 FROM sys.check_constraints WHERE name = N'CK_Books_TargetWordCount' AND parent_object_id = OBJECT_ID(N'dbo.Books'))
    ALTER TABLE dbo.Books ADD CONSTRAINT CK_Books_TargetWordCount CHECK (TargetWordCount IS NULL OR TargetWordCount > 0);
GO

CREATE OR ALTER PROCEDURE dbo.Book_ListByProject
    @ProjectID int
AS
BEGIN
    SET NOCOUNT ON;

    SELECT
        b.BookID,
        b.ProjectID,
        b.BookTitle,
        b.Subtitle,
        b.Tagline,
        b.ShortDescription,
        b.Status,
        b.BookNumber,
        b.Description,
        b.TargetWordCount,
        b.WritingStartDate,
        b.TargetCompletionDate,
        b.PublicationDate,
        ISNULL(wordCounts.CurrentWordCount, 0) AS CurrentWordCount,
        ISNULL(counts.ChapterCount, 0) AS ChapterCount,
        ISNULL(counts.SceneCount, 0) AS SceneCount,
        b.SortOrder,
        b.CreatedDate,
        b.UpdatedDate,
        b.IsArchived,
        b.ArchivedDate,
        b.ArchivedReason
    FROM dbo.Books b
    OUTER APPLY
    (
        SELECT
            COUNT(DISTINCT c.ChapterID) AS ChapterCount,
            COUNT(s.SceneID) AS SceneCount
        FROM dbo.Chapters c
        LEFT JOIN dbo.Scenes s ON s.ChapterID = c.ChapterID AND s.IsArchived = 0
        WHERE c.BookID = b.BookID AND c.IsArchived = 0
    ) counts
    OUTER APPLY
    (
        SELECT SUM(ISNULL(sw.ActualWordCount, 0)) AS CurrentWordCount
        FROM dbo.Chapters c
        INNER JOIN dbo.Scenes s ON s.ChapterID = c.ChapterID AND s.IsArchived = 0
        LEFT JOIN dbo.SceneWorkflow sw ON sw.SceneID = s.SceneID
        WHERE c.BookID = b.BookID AND c.IsArchived = 0
    ) wordCounts
    WHERE b.ProjectID = @ProjectID AND b.IsArchived = 0
    ORDER BY b.SortOrder, b.BookNumber, b.BookTitle;
END;
GO

CREATE OR ALTER PROCEDURE dbo.Book_Get
    @BookID int
AS
BEGIN
    SET NOCOUNT ON;

    SELECT
        b.BookID,
        b.ProjectID,
        b.BookTitle,
        b.Subtitle,
        b.Tagline,
        b.ShortDescription,
        b.Status,
        b.BookNumber,
        b.Description,
        b.TargetWordCount,
        b.WritingStartDate,
        b.TargetCompletionDate,
        b.PublicationDate,
        ISNULL(wordCounts.CurrentWordCount, 0) AS CurrentWordCount,
        ISNULL(counts.ChapterCount, 0) AS ChapterCount,
        ISNULL(counts.SceneCount, 0) AS SceneCount,
        b.SortOrder,
        b.CreatedDate,
        b.UpdatedDate,
        b.IsArchived,
        b.ArchivedDate,
        b.ArchivedReason
    FROM dbo.Books b
    OUTER APPLY
    (
        SELECT
            COUNT(DISTINCT c.ChapterID) AS ChapterCount,
            COUNT(s.SceneID) AS SceneCount
        FROM dbo.Chapters c
        LEFT JOIN dbo.Scenes s ON s.ChapterID = c.ChapterID AND s.IsArchived = 0
        WHERE c.BookID = b.BookID AND c.IsArchived = 0
    ) counts
    OUTER APPLY
    (
        SELECT SUM(ISNULL(sw.ActualWordCount, 0)) AS CurrentWordCount
        FROM dbo.Chapters c
        INNER JOIN dbo.Scenes s ON s.ChapterID = c.ChapterID AND s.IsArchived = 0
        LEFT JOIN dbo.SceneWorkflow sw ON sw.SceneID = s.SceneID
        WHERE c.BookID = b.BookID AND c.IsArchived = 0
    ) wordCounts
    WHERE b.BookID = @BookID AND b.IsArchived = 0;
END;
GO

CREATE OR ALTER PROCEDURE dbo.Book_Save
    @BookID int = NULL,
    @ProjectID int,
    @BookTitle nvarchar(200),
    @Subtitle nvarchar(200) = NULL,
    @Tagline nvarchar(300) = NULL,
    @ShortDescription nvarchar(max) = NULL,
    @Status nvarchar(50) = N'Planning',
    @BookNumber int,
    @Description nvarchar(max) = NULL,
    @TargetWordCount int = NULL,
    @WritingStartDate date = NULL,
    @TargetCompletionDate date = NULL,
    @PublicationDate date = NULL
AS
BEGIN
    SET NOCOUNT ON;

    IF @TargetWordCount IS NOT NULL AND @TargetWordCount <= 0
        THROW 51000, 'Target word count must be greater than zero.', 1;

    IF NULLIF(LTRIM(RTRIM(@Status)), N'') IS NULL
        SET @Status = N'Planning';

    IF @BookID IS NULL OR @BookID = 0
    BEGIN
        DECLARE @NextBookOrder int = ISNULL((SELECT MAX(SortOrder) FROM dbo.Books WHERE ProjectID = @ProjectID), 0) + 10;

        INSERT dbo.Books
        (
            ProjectID,
            BookTitle,
            Subtitle,
            Tagline,
            ShortDescription,
            Status,
            BookNumber,
            Description,
            TargetWordCount,
            WritingStartDate,
            TargetCompletionDate,
            PublicationDate,
            SortOrder
        )
        VALUES
        (
            @ProjectID,
            @BookTitle,
            @Subtitle,
            @Tagline,
            @ShortDescription,
            @Status,
            @BookNumber,
            @Description,
            @TargetWordCount,
            @WritingStartDate,
            @TargetCompletionDate,
            @PublicationDate,
            @NextBookOrder
        );

        SELECT CAST(SCOPE_IDENTITY() AS int) AS BookID;
        RETURN;
    END;

    UPDATE dbo.Books
    SET BookTitle = @BookTitle,
        Subtitle = @Subtitle,
        Tagline = @Tagline,
        ShortDescription = @ShortDescription,
        Status = @Status,
        BookNumber = @BookNumber,
        Description = @Description,
        TargetWordCount = @TargetWordCount,
        WritingStartDate = @WritingStartDate,
        TargetCompletionDate = @TargetCompletionDate,
        PublicationDate = @PublicationDate,
        UpdatedDate = SYSUTCDATETIME()
    WHERE BookID = @BookID;

    SELECT @BookID AS BookID;
END;
GO
