SET ANSI_NULLS ON;
GO
SET QUOTED_IDENTIFIER ON;
GO

DECLARE @ArchiveTables TABLE (TableName sysname);
INSERT @ArchiveTables (TableName)
VALUES
    (N'Projects'), (N'Books'), (N'Chapters'), (N'Scenes'), (N'PlotLines'), (N'PlotThreads'),
    (N'StoryAssets'), (N'Characters'), (N'Locations'), (N'Scenarios'), (N'CharacterRelationships');

DECLARE @TableName sysname;
DECLARE @Sql nvarchar(max);
DECLARE archive_cursor CURSOR LOCAL FAST_FORWARD FOR SELECT TableName FROM @ArchiveTables;
OPEN archive_cursor;
FETCH NEXT FROM archive_cursor INTO @TableName;
WHILE @@FETCH_STATUS = 0
BEGIN
    IF COL_LENGTH(N'dbo.' + @TableName, N'IsArchived') IS NULL
    BEGIN
        SET @Sql = N'ALTER TABLE dbo.' + QUOTENAME(@TableName) + N' ADD IsArchived bit NOT NULL CONSTRAINT ' + QUOTENAME(N'DF_' + @TableName + N'_IsArchived_Phase1T') + N' DEFAULT 0;';
        EXEC sys.sp_executesql @Sql;
    END

    IF COL_LENGTH(N'dbo.' + @TableName, N'ArchivedDate') IS NULL
    BEGIN
        SET @Sql = N'ALTER TABLE dbo.' + QUOTENAME(@TableName) + N' ADD ArchivedDate datetime2 NULL;';
        EXEC sys.sp_executesql @Sql;
    END

    IF COL_LENGTH(N'dbo.' + @TableName, N'ArchivedReason') IS NULL
    BEGIN
        SET @Sql = N'ALTER TABLE dbo.' + QUOTENAME(@TableName) + N' ADD ArchivedReason nvarchar(500) NULL;';
        EXEC sys.sp_executesql @Sql;
    END

    FETCH NEXT FROM archive_cursor INTO @TableName;
END
CLOSE archive_cursor;
DEALLOCATE archive_cursor;
GO

CREATE OR ALTER PROCEDURE dbo.Archive_List
    @ProjectID int = NULL,
    @EntityType nvarchar(80) = NULL
AS
BEGIN
    SET NOCOUNT ON;

    SELECT EntityType, EntityID, DisplayName, ProjectID, ProjectName, BookID, BookTitle, ArchivedDate, ArchivedReason, UpdatedDate
    FROM
    (
        SELECT N'Project' AS EntityType, p.ProjectID AS EntityID, p.ProjectName AS DisplayName, p.ProjectID, p.ProjectName,
            CAST(NULL AS int) AS BookID, CAST(NULL AS nvarchar(200)) AS BookTitle, p.ArchivedDate, p.ArchivedReason, p.UpdatedDate
        FROM dbo.Projects p
        WHERE p.IsArchived = 1

        UNION ALL
        SELECT N'Book', b.BookID, b.BookTitle, b.ProjectID, p.ProjectName, b.BookID, b.BookTitle, b.ArchivedDate, b.ArchivedReason, b.UpdatedDate
        FROM dbo.Books b INNER JOIN dbo.Projects p ON p.ProjectID = b.ProjectID
        WHERE b.IsArchived = 1

        UNION ALL
        SELECT N'Chapter', c.ChapterID, CONCAT(N'Ch ', c.ChapterNumber, N': ', c.ChapterTitle), b.ProjectID, p.ProjectName, b.BookID, b.BookTitle, c.ArchivedDate, c.ArchivedReason, c.UpdatedDate
        FROM dbo.Chapters c INNER JOIN dbo.Books b ON b.BookID = c.BookID INNER JOIN dbo.Projects p ON p.ProjectID = b.ProjectID
        WHERE c.IsArchived = 1

        UNION ALL
        SELECT N'Scene', s.SceneID, CONCAT(N'Scene ', s.SceneNumber, N': ', s.SceneTitle), b.ProjectID, p.ProjectName, b.BookID, b.BookTitle, s.ArchivedDate, s.ArchivedReason, s.UpdatedDate
        FROM dbo.Scenes s INNER JOIN dbo.Chapters c ON c.ChapterID = s.ChapterID INNER JOIN dbo.Books b ON b.BookID = c.BookID INNER JOIN dbo.Projects p ON p.ProjectID = b.ProjectID
        WHERE s.IsArchived = 1

        UNION ALL
        SELECT N'PlotLine', pl.PlotLineID, pl.PlotLineName, pl.ProjectID, p.ProjectName, pl.BookID, b.BookTitle, pl.ArchivedDate, pl.ArchivedReason, pl.UpdatedDate
        FROM dbo.PlotLines pl INNER JOIN dbo.Projects p ON p.ProjectID = pl.ProjectID LEFT JOIN dbo.Books b ON b.BookID = pl.BookID
        WHERE pl.IsArchived = 1

        UNION ALL
        SELECT N'PlotThread', pt.PlotThreadID, pt.ThreadTitle, pl.ProjectID, p.ProjectName, pl.BookID, b.BookTitle, pt.ArchivedDate, pt.ArchivedReason, pt.UpdatedDate
        FROM dbo.PlotThreads pt INNER JOIN dbo.PlotLines pl ON pl.PlotLineID = pt.PlotLineID INNER JOIN dbo.Projects p ON p.ProjectID = pl.ProjectID LEFT JOIN dbo.Books b ON b.BookID = pl.BookID
        WHERE pt.IsArchived = 1

        UNION ALL
        SELECT N'StoryAsset', sa.StoryAssetID, sa.AssetName, sa.ProjectID, p.ProjectName, CAST(NULL AS int), CAST(NULL AS nvarchar(200)), sa.ArchivedDate, sa.ArchivedReason, sa.UpdatedDate
        FROM dbo.StoryAssets sa INNER JOIN dbo.Projects p ON p.ProjectID = sa.ProjectID
        WHERE sa.IsArchived = 1

        UNION ALL
        SELECT N'Character', ch.CharacterID, ch.CharacterName, ch.ProjectID, p.ProjectName, CAST(NULL AS int), CAST(NULL AS nvarchar(200)), ch.ArchivedDate, ch.ArchivedReason, ch.UpdatedDate
        FROM dbo.Characters ch INNER JOIN dbo.Projects p ON p.ProjectID = ch.ProjectID
        WHERE ch.IsArchived = 1

        UNION ALL
        SELECT N'Location', l.LocationID, l.LocationName, l.ProjectID, p.ProjectName, CAST(NULL AS int), CAST(NULL AS nvarchar(200)), l.ArchivedDate, l.ArchivedReason, l.UpdatedDate
        FROM dbo.Locations l INNER JOIN dbo.Projects p ON p.ProjectID = l.ProjectID
        WHERE l.IsArchived = 1

        UNION ALL
        SELECT N'Scenario', sc.ScenarioID, sc.ScenarioName, sc.ProjectID, p.ProjectName, sc.BookID, b.BookTitle, sc.ArchivedDate, sc.ArchivedReason, sc.UpdatedDate
        FROM dbo.Scenarios sc INNER JOIN dbo.Projects p ON p.ProjectID = sc.ProjectID LEFT JOIN dbo.Books b ON b.BookID = sc.BookID
        WHERE sc.IsArchived = 1

        UNION ALL
        SELECT N'Relationship', cr.CharacterRelationshipID, CONCAT(ca.CharacterName, N' / ', cb.CharacterName), cr.ProjectID, p.ProjectName, CAST(NULL AS int), CAST(NULL AS nvarchar(200)), cr.ArchivedDate, cr.ArchivedReason, cr.UpdatedDate
        FROM dbo.CharacterRelationships cr INNER JOIN dbo.Projects p ON p.ProjectID = cr.ProjectID INNER JOIN dbo.Characters ca ON ca.CharacterID = cr.CharacterAID INNER JOIN dbo.Characters cb ON cb.CharacterID = cr.CharacterBID
        WHERE cr.IsArchived = 1
    ) archived
    WHERE (@ProjectID IS NULL OR archived.ProjectID = @ProjectID)
        AND (@EntityType IS NULL OR archived.EntityType = @EntityType)
    ORDER BY ISNULL(ArchivedDate, UpdatedDate) DESC, EntityType, DisplayName;
END;
GO

CREATE OR ALTER PROCEDURE dbo.Archive_Entity
    @EntityType nvarchar(80),
    @EntityID int,
    @ArchivedReason nvarchar(500) = NULL
AS
BEGIN
    SET NOCOUNT ON;

    IF @EntityType = N'Project' UPDATE dbo.Projects SET IsArchived = 1, ArchivedDate = SYSUTCDATETIME(), ArchivedReason = @ArchivedReason, UpdatedDate = SYSUTCDATETIME() WHERE ProjectID = @EntityID;
    ELSE IF @EntityType = N'Book' UPDATE dbo.Books SET IsArchived = 1, ArchivedDate = SYSUTCDATETIME(), ArchivedReason = @ArchivedReason, UpdatedDate = SYSUTCDATETIME() WHERE BookID = @EntityID;
    ELSE IF @EntityType = N'Chapter' UPDATE dbo.Chapters SET IsArchived = 1, ArchivedDate = SYSUTCDATETIME(), ArchivedReason = @ArchivedReason, UpdatedDate = SYSUTCDATETIME() WHERE ChapterID = @EntityID;
    ELSE IF @EntityType = N'Scene' UPDATE dbo.Scenes SET IsArchived = 1, ArchivedDate = SYSUTCDATETIME(), ArchivedReason = @ArchivedReason, UpdatedDate = SYSUTCDATETIME() WHERE SceneID = @EntityID;
    ELSE IF @EntityType = N'PlotLine' UPDATE dbo.PlotLines SET IsArchived = 1, ArchivedDate = SYSUTCDATETIME(), ArchivedReason = @ArchivedReason, UpdatedDate = SYSUTCDATETIME() WHERE PlotLineID = @EntityID;
    ELSE IF @EntityType = N'PlotThread' UPDATE dbo.PlotThreads SET IsArchived = 1, ArchivedDate = SYSUTCDATETIME(), ArchivedReason = @ArchivedReason, UpdatedDate = SYSUTCDATETIME() WHERE PlotThreadID = @EntityID;
    ELSE IF @EntityType = N'StoryAsset' UPDATE dbo.StoryAssets SET IsArchived = 1, ArchivedDate = SYSUTCDATETIME(), ArchivedReason = @ArchivedReason, UpdatedDate = SYSUTCDATETIME() WHERE StoryAssetID = @EntityID;
    ELSE IF @EntityType = N'Character' UPDATE dbo.Characters SET IsArchived = 1, ArchivedDate = SYSUTCDATETIME(), ArchivedReason = @ArchivedReason, UpdatedDate = SYSUTCDATETIME() WHERE CharacterID = @EntityID;
    ELSE IF @EntityType = N'Location' UPDATE dbo.Locations SET IsArchived = 1, ArchivedDate = SYSUTCDATETIME(), ArchivedReason = @ArchivedReason, UpdatedDate = SYSUTCDATETIME() WHERE LocationID = @EntityID;
    ELSE IF @EntityType = N'Scenario' UPDATE dbo.Scenarios SET IsArchived = 1, ArchivedDate = SYSUTCDATETIME(), ArchivedReason = @ArchivedReason, UpdatedDate = SYSUTCDATETIME() WHERE ScenarioID = @EntityID;
    ELSE IF @EntityType = N'Relationship' UPDATE dbo.CharacterRelationships SET IsArchived = 1, ArchivedDate = SYSUTCDATETIME(), ArchivedReason = @ArchivedReason, UpdatedDate = SYSUTCDATETIME() WHERE CharacterRelationshipID = @EntityID;
END;
GO

CREATE OR ALTER PROCEDURE dbo.Archive_Restore
    @EntityType nvarchar(80),
    @EntityID int
AS
BEGIN
    SET NOCOUNT ON;

    IF @EntityType = N'Project' UPDATE dbo.Projects SET IsArchived = 0, ArchivedDate = NULL, ArchivedReason = NULL, UpdatedDate = SYSUTCDATETIME() WHERE ProjectID = @EntityID;
    ELSE IF @EntityType = N'Book' UPDATE dbo.Books SET IsArchived = 0, ArchivedDate = NULL, ArchivedReason = NULL, UpdatedDate = SYSUTCDATETIME() WHERE BookID = @EntityID;
    ELSE IF @EntityType = N'Chapter' UPDATE dbo.Chapters SET IsArchived = 0, ArchivedDate = NULL, ArchivedReason = NULL, UpdatedDate = SYSUTCDATETIME() WHERE ChapterID = @EntityID;
    ELSE IF @EntityType = N'Scene' UPDATE dbo.Scenes SET IsArchived = 0, ArchivedDate = NULL, ArchivedReason = NULL, UpdatedDate = SYSUTCDATETIME() WHERE SceneID = @EntityID;
    ELSE IF @EntityType = N'PlotLine' UPDATE dbo.PlotLines SET IsArchived = 0, ArchivedDate = NULL, ArchivedReason = NULL, UpdatedDate = SYSUTCDATETIME() WHERE PlotLineID = @EntityID;
    ELSE IF @EntityType = N'PlotThread' UPDATE dbo.PlotThreads SET IsArchived = 0, ArchivedDate = NULL, ArchivedReason = NULL, UpdatedDate = SYSUTCDATETIME() WHERE PlotThreadID = @EntityID;
    ELSE IF @EntityType = N'StoryAsset' UPDATE dbo.StoryAssets SET IsArchived = 0, ArchivedDate = NULL, ArchivedReason = NULL, UpdatedDate = SYSUTCDATETIME() WHERE StoryAssetID = @EntityID;
    ELSE IF @EntityType = N'Character' UPDATE dbo.Characters SET IsArchived = 0, ArchivedDate = NULL, ArchivedReason = NULL, UpdatedDate = SYSUTCDATETIME() WHERE CharacterID = @EntityID;
    ELSE IF @EntityType = N'Location' UPDATE dbo.Locations SET IsArchived = 0, ArchivedDate = NULL, ArchivedReason = NULL, UpdatedDate = SYSUTCDATETIME() WHERE LocationID = @EntityID;
    ELSE IF @EntityType = N'Scenario' UPDATE dbo.Scenarios SET IsArchived = 0, ArchivedDate = NULL, ArchivedReason = NULL, UpdatedDate = SYSUTCDATETIME() WHERE ScenarioID = @EntityID;
    ELSE IF @EntityType = N'Relationship' UPDATE dbo.CharacterRelationships SET IsArchived = 0, ArchivedDate = NULL, ArchivedReason = NULL, UpdatedDate = SYSUTCDATETIME() WHERE CharacterRelationshipID = @EntityID;
END;
GO

CREATE OR ALTER PROCEDURE dbo.Archive_ProjectFilterList
AS
BEGIN
    SET NOCOUNT ON;

    SELECT ProjectID, ProjectName, Description, CreatedDate, UpdatedDate, IsArchived
    FROM dbo.Projects
    ORDER BY IsArchived, ProjectName;
END;
GO

CREATE OR ALTER PROCEDURE dbo.Archive_DeleteForever
    @EntityType nvarchar(80),
    @EntityID int,
    @ConfirmationText nvarchar(20)
AS
BEGIN
    SET NOCOUNT ON;

    IF UPPER(LTRIM(RTRIM(ISNULL(@ConfirmationText, N'')))) <> N'DELETE'
    BEGIN
        SELECT CAST(0 AS bit) AS Succeeded, N'Type DELETE to permanently delete an archived item.' AS Message;
        RETURN;
    END;

    DECLARE @HasLinks bit = 0;
    DECLARE @IsArchived bit = 0;

    IF @EntityType = N'Project'
    BEGIN
        SELECT @IsArchived = IsArchived FROM dbo.Projects WHERE ProjectID = @EntityID;
        IF EXISTS (
            SELECT 1 FROM dbo.Books WHERE ProjectID = @EntityID
            UNION ALL SELECT 1 FROM dbo.PlotLines WHERE ProjectID = @EntityID
            UNION ALL SELECT 1 FROM dbo.StoryAssets WHERE ProjectID = @EntityID
            UNION ALL SELECT 1 FROM dbo.Characters WHERE ProjectID = @EntityID
            UNION ALL SELECT 1 FROM dbo.Locations WHERE ProjectID = @EntityID
            UNION ALL SELECT 1 FROM dbo.Scenarios WHERE ProjectID = @EntityID
        ) SET @HasLinks = 1;
        IF @IsArchived = 1 AND @HasLinks = 0 DELETE FROM dbo.Projects WHERE ProjectID = @EntityID;
    END
    ELSE IF @EntityType = N'Book'
    BEGIN
        SELECT @IsArchived = IsArchived FROM dbo.Books WHERE BookID = @EntityID;
        IF EXISTS (
            SELECT 1 FROM dbo.Chapters WHERE BookID = @EntityID
            UNION ALL SELECT 1 FROM dbo.PlotLines WHERE BookID = @EntityID
            UNION ALL SELECT 1 FROM dbo.Scenarios WHERE BookID = @EntityID
        ) SET @HasLinks = 1;
        IF @IsArchived = 1 AND @HasLinks = 0 DELETE FROM dbo.Books WHERE BookID = @EntityID;
    END
    ELSE IF @EntityType = N'Chapter'
    BEGIN
        SELECT @IsArchived = IsArchived FROM dbo.Chapters WHERE ChapterID = @EntityID;
        IF EXISTS (SELECT 1 FROM dbo.Scenes WHERE ChapterID = @EntityID) SET @HasLinks = 1;
        IF @IsArchived = 1 AND @HasLinks = 0 DELETE FROM dbo.Chapters WHERE ChapterID = @EntityID;
    END
    ELSE IF @EntityType = N'Scene'
    BEGIN
        SELECT @IsArchived = IsArchived FROM dbo.Scenes WHERE SceneID = @EntityID;
        IF EXISTS (
            SELECT 1 FROM dbo.ScenePurposes WHERE SceneID = @EntityID
            UNION ALL SELECT 1 FROM dbo.SceneMetricValues WHERE SceneID = @EntityID
            UNION ALL SELECT 1 FROM dbo.ThreadEvents WHERE SceneID = @EntityID
            UNION ALL SELECT 1 FROM dbo.AssetEvents WHERE SceneID = @EntityID
            UNION ALL SELECT 1 FROM dbo.SceneCharacters WHERE SceneID = @EntityID
            UNION ALL SELECT 1 FROM dbo.CharacterKnowledge WHERE SceneID = @EntityID
            UNION ALL SELECT 1 FROM dbo.RelationshipEvents WHERE SceneID = @EntityID
            UNION ALL SELECT 1 FROM dbo.SceneNotes WHERE SceneID = @EntityID
            UNION ALL SELECT 1 FROM dbo.SceneChecklistItems WHERE SceneID = @EntityID
            UNION ALL SELECT 1 FROM dbo.SceneAttachments WHERE SceneID = @EntityID
            UNION ALL SELECT 1 FROM dbo.ScenarioSceneOrder WHERE SceneID = @EntityID
        ) SET @HasLinks = 1;
        IF @IsArchived = 1 AND @HasLinks = 0 DELETE FROM dbo.Scenes WHERE SceneID = @EntityID;
    END
    ELSE IF @EntityType = N'PlotLine'
    BEGIN
        SELECT @IsArchived = IsArchived FROM dbo.PlotLines WHERE PlotLineID = @EntityID;
        IF EXISTS (SELECT 1 FROM dbo.PlotThreads WHERE PlotLineID = @EntityID) SET @HasLinks = 1;
        IF @IsArchived = 1 AND @HasLinks = 0 DELETE FROM dbo.PlotLines WHERE PlotLineID = @EntityID;
    END
    ELSE IF @EntityType = N'PlotThread'
    BEGIN
        SELECT @IsArchived = IsArchived FROM dbo.PlotThreads WHERE PlotThreadID = @EntityID;
        IF EXISTS (
            SELECT 1 FROM dbo.ThreadEvents WHERE PlotThreadID = @EntityID
            UNION ALL SELECT 1 FROM dbo.CharacterKnowledge WHERE PlotThreadID = @EntityID
        ) SET @HasLinks = 1;
        IF @IsArchived = 1 AND @HasLinks = 0 DELETE FROM dbo.PlotThreads WHERE PlotThreadID = @EntityID;
    END
    ELSE IF @EntityType = N'StoryAsset'
    BEGIN
        SELECT @IsArchived = IsArchived FROM dbo.StoryAssets WHERE StoryAssetID = @EntityID;
        IF EXISTS (
            SELECT 1 FROM dbo.AssetEvents WHERE StoryAssetID = @EntityID
            UNION ALL SELECT 1 FROM dbo.AssetDependencies WHERE SourceAssetID = @EntityID OR TargetAssetID = @EntityID
            UNION ALL SELECT 1 FROM dbo.AssetCustodyEvents WHERE StoryAssetID = @EntityID
            UNION ALL SELECT 1 FROM dbo.CharacterKnowledge WHERE StoryAssetID = @EntityID
            UNION ALL SELECT 1 FROM dbo.SceneAssetLocations WHERE StoryAssetID = @EntityID
        ) SET @HasLinks = 1;
        IF @IsArchived = 1 AND @HasLinks = 0 DELETE FROM dbo.StoryAssets WHERE StoryAssetID = @EntityID;
    END
    ELSE IF @EntityType = N'Character'
    BEGIN
        SELECT @IsArchived = IsArchived FROM dbo.Characters WHERE CharacterID = @EntityID;
        IF EXISTS (
            SELECT 1 FROM dbo.SceneCharacters WHERE CharacterID = @EntityID
            UNION ALL SELECT 1 FROM dbo.CharacterAttributeEvents WHERE CharacterID = @EntityID
            UNION ALL SELECT 1 FROM dbo.CharacterKnowledge WHERE CharacterID = @EntityID
            UNION ALL SELECT 1 FROM dbo.CharacterRelationships WHERE CharacterAID = @EntityID OR CharacterBID = @EntityID
        ) SET @HasLinks = 1;
        IF @IsArchived = 1 AND @HasLinks = 0 DELETE FROM dbo.Characters WHERE CharacterID = @EntityID;
    END
    ELSE IF @EntityType = N'Location'
    BEGIN
        SELECT @IsArchived = IsArchived FROM dbo.Locations WHERE LocationID = @EntityID;
        IF EXISTS (
            SELECT 1 FROM dbo.Locations WHERE ParentLocationID = @EntityID
            UNION ALL SELECT 1 FROM dbo.Scenes WHERE PrimaryLocationID = @EntityID
            UNION ALL SELECT 1 FROM dbo.SceneCharacters WHERE LocationID = @EntityID OR EntryLocationID = @EntityID OR ExitLocationID = @EntityID
            UNION ALL SELECT 1 FROM dbo.StoryAssets WHERE CurrentLocationID = @EntityID
            UNION ALL SELECT 1 FROM dbo.SceneAssetLocations WHERE LocationID = @EntityID
            UNION ALL SELECT 1 FROM dbo.LocationRelationships WHERE FromLocationID = @EntityID OR ToLocationID = @EntityID
        ) SET @HasLinks = 1;
        IF @IsArchived = 1 AND @HasLinks = 0 DELETE FROM dbo.Locations WHERE LocationID = @EntityID;
    END
    ELSE IF @EntityType = N'Scenario'
    BEGIN
        SELECT @IsArchived = IsArchived FROM dbo.Scenarios WHERE ScenarioID = @EntityID;
        IF EXISTS (
            SELECT 1 FROM dbo.ScenarioSceneOrder WHERE ScenarioID = @EntityID
            UNION ALL SELECT 1 FROM dbo.ScenarioWarnings WHERE ScenarioID = @EntityID
        ) SET @HasLinks = 1;
        IF @IsArchived = 1 AND @HasLinks = 0 DELETE FROM dbo.Scenarios WHERE ScenarioID = @EntityID;
    END
    ELSE IF @EntityType = N'Relationship'
    BEGIN
        SELECT @IsArchived = IsArchived FROM dbo.CharacterRelationships WHERE CharacterRelationshipID = @EntityID;
        IF EXISTS (SELECT 1 FROM dbo.RelationshipEvents WHERE CharacterRelationshipID = @EntityID) SET @HasLinks = 1;
        IF @IsArchived = 1 AND @HasLinks = 0 DELETE FROM dbo.CharacterRelationships WHERE CharacterRelationshipID = @EntityID;
    END
    ELSE
    BEGIN
        SELECT CAST(0 AS bit) AS Succeeded, N'This archived item type is not supported for permanent delete.' AS Message;
        RETURN;
    END;

    IF ISNULL(@IsArchived, 0) = 0
    BEGIN
        SELECT CAST(0 AS bit) AS Succeeded, N'Only archived items can be permanently deleted.' AS Message;
        RETURN;
    END;

    IF @HasLinks = 1
    BEGIN
        SELECT CAST(0 AS bit) AS Succeeded, N'This item has linked story data and cannot yet be permanently deleted safely. Leave it archived instead.' AS Message;
        RETURN;
    END;

    SELECT CAST(1 AS bit) AS Succeeded, N'Archived item permanently deleted.' AS Message;
END;
GO

CREATE OR ALTER PROCEDURE dbo.Project_Archive @ProjectID int AS BEGIN SET NOCOUNT ON; EXEC dbo.Archive_Entity N'Project', @ProjectID, NULL; END;
GO
CREATE OR ALTER PROCEDURE dbo.Book_Archive @BookID int AS BEGIN SET NOCOUNT ON; EXEC dbo.Archive_Entity N'Book', @BookID, NULL; END;
GO
CREATE OR ALTER PROCEDURE dbo.Chapter_Archive @ChapterID int AS BEGIN SET NOCOUNT ON; EXEC dbo.Archive_Entity N'Chapter', @ChapterID, NULL; END;
GO
CREATE OR ALTER PROCEDURE dbo.Scene_Archive @SceneID int AS BEGIN SET NOCOUNT ON; EXEC dbo.Archive_Entity N'Scene', @SceneID, NULL; END;
GO
CREATE OR ALTER PROCEDURE dbo.PlotLine_Archive @PlotLineID int AS BEGIN SET NOCOUNT ON; EXEC dbo.Archive_Entity N'PlotLine', @PlotLineID, NULL; END;
GO
CREATE OR ALTER PROCEDURE dbo.PlotThread_Archive @PlotThreadID int AS BEGIN SET NOCOUNT ON; EXEC dbo.Archive_Entity N'PlotThread', @PlotThreadID, NULL; END;
GO
CREATE OR ALTER PROCEDURE dbo.StoryAsset_Archive @StoryAssetID int AS BEGIN SET NOCOUNT ON; EXEC dbo.Archive_Entity N'StoryAsset', @StoryAssetID, NULL; END;
GO
CREATE OR ALTER PROCEDURE dbo.Character_Archive @CharacterID int AS BEGIN SET NOCOUNT ON; EXEC dbo.Archive_Entity N'Character', @CharacterID, NULL; END;
GO
CREATE OR ALTER PROCEDURE dbo.Location_Archive @LocationID int AS BEGIN SET NOCOUNT ON; EXEC dbo.Archive_Entity N'Location', @LocationID, NULL; END;
GO
CREATE OR ALTER PROCEDURE dbo.Scenario_Archive @ScenarioID int AS BEGIN SET NOCOUNT ON; EXEC dbo.Archive_Entity N'Scenario', @ScenarioID, NULL; END;
GO
CREATE OR ALTER PROCEDURE dbo.Relationship_Archive @CharacterRelationshipID int AS BEGIN SET NOCOUNT ON; EXEC dbo.Archive_Entity N'Relationship', @CharacterRelationshipID, NULL; END;
GO

CREATE OR ALTER PROCEDURE dbo.SceneCharacter_ListByScene
    @SceneID int
AS
BEGIN
    SET NOCOUNT ON;
    SELECT sc.SceneCharacterID, sc.SceneID, sc.CharacterID, c.ProjectID,
        CASE WHEN c.IsArchived = 1 THEN CONCAT(c.CharacterName, N' (archived)') ELSE c.CharacterName END AS CharacterName,
        c.ShortName, c.BirthDate, c.AgeAtSeriesStart,
        sc.RoleInSceneTypeID, role.TypeName AS RoleInSceneTypeName, sc.PresenceTypeID, presence.TypeName AS PresenceTypeName,
        sc.AppearanceNotes, sc.OutfitDescription, sc.PhysicalCondition, sc.EmotionalState, sc.KnowledgeNotes,
        sc.CreatedDate, sc.UpdatedDate
    FROM dbo.SceneCharacters sc
    INNER JOIN dbo.Characters c ON c.CharacterID = sc.CharacterID
    LEFT JOIN dbo.CharacterRoleInSceneTypes role ON role.CharacterRoleInSceneTypeID = sc.RoleInSceneTypeID
    LEFT JOIN dbo.PresenceTypes presence ON presence.PresenceTypeID = sc.PresenceTypeID
    WHERE sc.SceneID = @SceneID
    ORDER BY role.SortOrder, c.CharacterName;
END;
GO

CREATE OR ALTER PROCEDURE dbo.ThreadEvent_ListByScene
    @SceneID int
AS
BEGIN
    SET NOCOUNT ON;
    SELECT te.ThreadEventID, te.PlotThreadID,
        CASE WHEN pt.IsArchived = 1 THEN CONCAT(pt.ThreadTitle, N' (archived)') ELSE pt.ThreadTitle END AS ThreadTitle,
        pt.PlotLineID,
        CASE WHEN pl.IsArchived = 1 THEN CONCAT(pl.PlotLineName, N' (archived)') ELSE pl.PlotLineName END AS PlotLineName,
        pl.Colour, te.SceneID, te.EventTypeID, tet.TypeName AS EventTypeName, tet.MarkerText, te.EventTitle,
        te.EventDescription, te.CreatedDate, te.UpdatedDate
    FROM dbo.ThreadEvents te
    INNER JOIN dbo.PlotThreads pt ON pt.PlotThreadID = te.PlotThreadID
    INNER JOIN dbo.PlotLines pl ON pl.PlotLineID = pt.PlotLineID
    INNER JOIN dbo.ThreadEventTypes tet ON tet.ThreadEventTypeID = te.EventTypeID
    WHERE te.SceneID = @SceneID
    ORDER BY pl.SortOrder, pt.Importance DESC, te.CreatedDate;
END;
GO

CREATE OR ALTER PROCEDURE dbo.AssetEvent_ListByScene
    @SceneID int
AS
BEGIN
    SET NOCOUNT ON;
    SELECT ae.AssetEventID, ae.StoryAssetID, sa.ProjectID,
        CASE WHEN sa.IsArchived = 1 THEN CONCAT(sa.AssetName, N' (archived)') ELSE sa.AssetName END AS AssetName,
        sa.AssetKindID, ak.KindName,
        ae.SceneID, ae.AssetEventTypeID, aet.TypeName AS AssetEventTypeName, aet.MarkerText,
        ae.FromStateID, fs.StateName AS FromStateName, ae.ToStateID, ts.StateName AS ToStateName,
        ae.EventTitle, ae.EventDescription, ae.CreatedDate, ae.UpdatedDate
    FROM dbo.AssetEvents ae
    INNER JOIN dbo.StoryAssets sa ON sa.StoryAssetID = ae.StoryAssetID
    INNER JOIN dbo.AssetKinds ak ON ak.AssetKindID = sa.AssetKindID
    INNER JOIN dbo.AssetEventTypes aet ON aet.AssetEventTypeID = ae.AssetEventTypeID
    LEFT JOIN dbo.AssetStates fs ON fs.AssetStateID = ae.FromStateID
    LEFT JOIN dbo.AssetStates ts ON ts.AssetStateID = ae.ToStateID
    WHERE ae.SceneID = @SceneID
    ORDER BY sa.AssetName, ae.AssetEventID;
END;
GO

CREATE OR ALTER PROCEDURE dbo.RelationshipEvent_ListByScene
    @SceneID int
AS
BEGIN
    SET NOCOUNT ON;
    SELECT re.RelationshipEventID, re.CharacterRelationshipID, cr.ProjectID, cr.CharacterAID,
        CASE WHEN ca.IsArchived = 1 THEN CONCAT(ca.CharacterName, N' (archived)') ELSE ca.CharacterName END AS CharacterAName,
        cr.CharacterBID,
        CASE WHEN cb.IsArchived = 1 THEN CONCAT(cb.CharacterName, N' (archived)') ELSE cb.CharacterName END AS CharacterBName,
        CASE WHEN cr.IsArchived = 1 THEN CONCAT(rt.TypeName, N' (archived)') ELSE rt.TypeName END AS RelationshipTypeName,
        re.SceneID, re.RelationshipStateID, rs.StateName AS RelationshipStateName, re.Intensity, re.IsKnownToOtherCharacter,
        re.Description, re.CreatedDate, re.UpdatedDate
    FROM dbo.RelationshipEvents re
    INNER JOIN dbo.CharacterRelationships cr ON cr.CharacterRelationshipID = re.CharacterRelationshipID
    INNER JOIN dbo.Characters ca ON ca.CharacterID = cr.CharacterAID
    INNER JOIN dbo.Characters cb ON cb.CharacterID = cr.CharacterBID
    INNER JOIN dbo.RelationshipTypes rt ON rt.RelationshipTypeID = cr.RelationshipTypeID
    INNER JOIN dbo.RelationshipStates rs ON rs.RelationshipStateID = re.RelationshipStateID
    WHERE re.SceneID = @SceneID
    ORDER BY ca.CharacterName, cb.CharacterName;
END;
GO

CREATE OR ALTER PROCEDURE dbo.CharacterKnowledge_Delete
    @CharacterKnowledgeID int
AS
BEGIN
    SET NOCOUNT ON;
    DELETE FROM dbo.CharacterKnowledge WHERE CharacterKnowledgeID = @CharacterKnowledgeID;
END;
GO

CREATE OR ALTER PROCEDURE dbo.RelationshipEvent_Delete
    @RelationshipEventID int
AS
BEGIN
    SET NOCOUNT ON;
    DELETE FROM dbo.RelationshipEvents WHERE RelationshipEventID = @RelationshipEventID;
END;
GO
