SET ANSI_NULLS ON;
GO
SET QUOTED_IDENTIFIER ON;
GO

IF OBJECT_ID(N'dbo.StoryIntelligenceImportCommits', N'U') IS NULL
BEGIN
    CREATE TABLE dbo.StoryIntelligenceImportCommits
    (
        StoryIntelligenceImportCommitID int IDENTITY(1,1) NOT NULL CONSTRAINT PK_StoryIntelligenceImportCommits PRIMARY KEY,
        StoryIntelligenceRunID int NOT NULL,
        ProjectID int NULL,
        BookID int NULL,
        ChapterID int NULL,
        CommittedAt datetime2 NOT NULL CONSTRAINT DF_StoryIntelligenceImportCommits_CommittedAt DEFAULT SYSUTCDATETIME(),
        CommittedByUserID int NOT NULL,
        ScenesCreated int NOT NULL CONSTRAINT DF_StoryIntelligenceImportCommits_ScenesCreated DEFAULT 0,
        MetricsCreated int NOT NULL CONSTRAINT DF_StoryIntelligenceImportCommits_MetricsCreated DEFAULT 0,
        Status nvarchar(40) NOT NULL,
        Notes nvarchar(max) NULL,
        CreatedUtc datetime2 NOT NULL CONSTRAINT DF_StoryIntelligenceImportCommits_CreatedUtc DEFAULT SYSUTCDATETIME(),
        CONSTRAINT FK_StoryIntelligenceImportCommits_Runs FOREIGN KEY (StoryIntelligenceRunID) REFERENCES dbo.StoryIntelligenceRuns(StoryIntelligenceRunID),
        CONSTRAINT FK_StoryIntelligenceImportCommits_Projects FOREIGN KEY (ProjectID) REFERENCES dbo.Projects(ProjectID),
        CONSTRAINT FK_StoryIntelligenceImportCommits_Books FOREIGN KEY (BookID) REFERENCES dbo.Books(BookID),
        CONSTRAINT FK_StoryIntelligenceImportCommits_Chapters FOREIGN KEY (ChapterID) REFERENCES dbo.Chapters(ChapterID),
        CONSTRAINT FK_StoryIntelligenceImportCommits_AppUser FOREIGN KEY (CommittedByUserID) REFERENCES dbo.AppUser(UserID)
    );
END;
GO

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'UX_StoryIntelligenceImportCommits_CompletedRun' AND object_id = OBJECT_ID(N'dbo.StoryIntelligenceImportCommits'))
    CREATE UNIQUE INDEX UX_StoryIntelligenceImportCommits_CompletedRun ON dbo.StoryIntelligenceImportCommits(StoryIntelligenceRunID) WHERE Status = N'Completed';
GO

IF COL_LENGTH(N'dbo.Scenes', N'ImportSource') IS NULL
    ALTER TABLE dbo.Scenes ADD ImportSource nvarchar(80) NULL;
GO
IF COL_LENGTH(N'dbo.Scenes', N'ImportRunID') IS NULL
    ALTER TABLE dbo.Scenes ADD ImportRunID int NULL;
GO
IF COL_LENGTH(N'dbo.Scenes', N'SourceStartParagraph') IS NULL
    ALTER TABLE dbo.Scenes ADD SourceStartParagraph int NULL;
GO
IF COL_LENGTH(N'dbo.Scenes', N'SourceEndParagraph') IS NULL
    ALTER TABLE dbo.Scenes ADD SourceEndParagraph int NULL;
GO

IF NOT EXISTS (SELECT 1 FROM sys.foreign_keys WHERE name = N'FK_Scenes_StoryIntelligenceRuns_ImportRunID')
    ALTER TABLE dbo.Scenes ADD CONSTRAINT FK_Scenes_StoryIntelligenceRuns_ImportRunID FOREIGN KEY (ImportRunID) REFERENCES dbo.StoryIntelligenceRuns(StoryIntelligenceRunID);
GO

CREATE OR ALTER PROCEDURE dbo.StoryIntelligenceImportCommit_GetByRun
    @StoryIntelligenceRunID int
AS
BEGIN
    SET NOCOUNT ON;

    SELECT TOP (1) StoryIntelligenceImportCommitID, StoryIntelligenceRunID, ProjectID, BookID, ChapterID,
        CommittedAt, CommittedByUserID, ScenesCreated, MetricsCreated, Status, Notes, CreatedUtc
    FROM dbo.StoryIntelligenceImportCommits
    WHERE StoryIntelligenceRunID = @StoryIntelligenceRunID
    ORDER BY CASE WHEN Status = N'Completed' THEN 0 ELSE 1 END, CreatedUtc DESC;
END;
GO

CREATE OR ALTER PROCEDURE dbo.StoryIntelligenceImportCommit_HasCompleted
    @StoryIntelligenceRunID int
AS
BEGIN
    SET NOCOUNT ON;
    SELECT CAST(CASE WHEN EXISTS
    (
        SELECT 1
        FROM dbo.StoryIntelligenceImportCommits
        WHERE StoryIntelligenceRunID = @StoryIntelligenceRunID
            AND Status = N'Completed'
    ) THEN 1 ELSE 0 END AS bit);
END;
GO

CREATE OR ALTER PROCEDURE dbo.StoryIntelligenceImportCommit_CountChapterScenes
    @ChapterID int
AS
BEGIN
    SET NOCOUNT ON;
    SELECT COUNT(1)
    FROM dbo.Scenes
    WHERE ChapterID = @ChapterID
        AND IsArchived = 0;
END;
GO

CREATE OR ALTER PROCEDURE dbo.StoryIntelligenceSceneSource_Save
    @SceneID int,
    @ImportSource nvarchar(80),
    @ImportRunID int,
    @SourceStartParagraph int = NULL,
    @SourceEndParagraph int = NULL
AS
BEGIN
    SET NOCOUNT ON;

    UPDATE dbo.Scenes
    SET ImportSource = @ImportSource,
        ImportRunID = @ImportRunID,
        SourceStartParagraph = @SourceStartParagraph,
        SourceEndParagraph = @SourceEndParagraph,
        UpdatedDate = SYSUTCDATETIME()
    WHERE SceneID = @SceneID;
END;
GO

CREATE OR ALTER PROCEDURE dbo.StoryIntelligenceImportCommit_RecordCompleted
    @StoryIntelligenceRunID int,
    @ProjectID int = NULL,
    @BookID int = NULL,
    @ChapterID int = NULL,
    @CommittedByUserID int,
    @ScenesCreated int,
    @MetricsCreated int,
    @Notes nvarchar(max) = NULL
AS
BEGIN
    SET NOCOUNT ON;

    INSERT dbo.StoryIntelligenceImportCommits
    (
        StoryIntelligenceRunID, ProjectID, BookID, ChapterID, CommittedAt, CommittedByUserID,
        ScenesCreated, MetricsCreated, Status, Notes
    )
    VALUES
    (
        @StoryIntelligenceRunID, @ProjectID, @BookID, @ChapterID, SYSUTCDATETIME(), @CommittedByUserID,
        @ScenesCreated, @MetricsCreated, N'Completed', @Notes
    );

    SELECT CAST(SCOPE_IDENTITY() AS int);
END;
GO

CREATE OR ALTER PROCEDURE dbo.StoryIntelligenceImportCommit_RecordFailed
    @StoryIntelligenceRunID int,
    @ProjectID int = NULL,
    @BookID int = NULL,
    @ChapterID int = NULL,
    @CommittedByUserID int,
    @ScenesCreated int,
    @MetricsCreated int,
    @Notes nvarchar(max) = NULL
AS
BEGIN
    SET NOCOUNT ON;

    INSERT dbo.StoryIntelligenceImportCommits
    (
        StoryIntelligenceRunID, ProjectID, BookID, ChapterID, CommittedAt, CommittedByUserID,
        ScenesCreated, MetricsCreated, Status, Notes
    )
    VALUES
    (
        @StoryIntelligenceRunID, @ProjectID, @BookID, @ChapterID, SYSUTCDATETIME(), @CommittedByUserID,
        @ScenesCreated, @MetricsCreated, N'Failed', @Notes
    );
END;
GO
