SET ANSI_NULLS ON;
GO
SET QUOTED_IDENTIFIER ON;
GO

CREATE OR ALTER PROCEDURE dbo.StoryIntelligenceImportCommit_GetChapterReadiness
    @ChapterID int
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @ActiveSceneCount int;
    DECLARE @SceneID int = NULL;
    DECLARE @CanCommit bit = 0;
    DECLARE @HasUntouchedDefaultPlaceholder bit = 0;
    DECLARE @CommitMode nvarchar(80) = N'Blocked';
    DECLARE @BlockReason nvarchar(300) = NULL;

    SELECT @ActiveSceneCount = COUNT(1)
    FROM dbo.Scenes
    WHERE ChapterID = @ChapterID
        AND IsArchived = 0;

    IF @ActiveSceneCount = 0
    BEGIN
        SELECT @ActiveSceneCount AS ActiveSceneCount, CAST(1 AS bit) AS CanCommit, CAST(0 AS bit) AS HasUntouchedDefaultPlaceholder,
            CAST(NULL AS int) AS PlaceholderSceneID, CAST(N'EmptyChapter' AS nvarchar(80)) AS CommitMode, CAST(NULL AS nvarchar(300)) AS BlockReason;
        RETURN;
    END;

    IF @ActiveSceneCount > 1
    BEGIN
        SELECT @ActiveSceneCount AS ActiveSceneCount, CAST(0 AS bit) AS CanCommit, CAST(0 AS bit) AS HasUntouchedDefaultPlaceholder,
            CAST(NULL AS int) AS PlaceholderSceneID, @CommitMode AS CommitMode, CAST(N'chapter contains existing authored scenes' AS nvarchar(300)) AS BlockReason;
        RETURN;
    END;

    SELECT TOP (1) @SceneID = SceneID
    FROM dbo.Scenes
    WHERE ChapterID = @ChapterID
        AND IsArchived = 0
    ORDER BY SceneNumber, SceneID;

    IF EXISTS
    (
        SELECT 1
        FROM dbo.Scenes
        WHERE SceneID = @SceneID
            AND SceneNumber = 1
            AND LTRIM(RTRIM(SceneTitle)) IN (N'Scene 1', N'Scene One', N'Untitled Scene', N'Untitled Scene 1')
            AND NULLIF(LTRIM(RTRIM(ISNULL(Summary, N''))), N'') IS NULL
            AND POVCharacterID IS NULL
            AND PrimaryLocationID IS NULL
            AND StartDateTime IS NULL
            AND EndDateTime IS NULL
            AND DurationAmount IS NULL
            AND DurationUnitID IS NULL
            AND NULLIF(LTRIM(RTRIM(ISNULL(RelativeTimeText, N''))), N'') IS NULL
            AND NULLIF(LTRIM(RTRIM(ISNULL(ScenePurposeNotes, N''))), N'') IS NULL
            AND NULLIF(LTRIM(RTRIM(ISNULL(SceneOutcomeNotes, N''))), N'') IS NULL
            AND ISNULL(FloorPlanID, 0) = 0
            AND ISNULL(InitialFloorPlanFloorID, 0) = 0
            AND NULLIF(LTRIM(RTRIM(ISNULL(ImportSource, N''))), N'') IS NULL
            AND ImportRunID IS NULL
            AND SourceStartParagraph IS NULL
            AND SourceEndParagraph IS NULL
    )
    BEGIN
        SET @CanCommit = 1;
    END
    ELSE
    BEGIN
        SELECT TOP (1) @BlockReason =
            CASE
                WHEN SceneNumber <> 1 THEN N'chapter contains existing authored scenes'
                WHEN LTRIM(RTRIM(SceneTitle)) NOT IN (N'Scene 1', N'Scene One', N'Untitled Scene', N'Untitled Scene 1') THEN N'chapter contains existing authored scenes'
                WHEN NULLIF(LTRIM(RTRIM(ISNULL(Summary, N''))), N'') IS NOT NULL THEN N'existing scene has summary text'
                WHEN POVCharacterID IS NOT NULL THEN N'existing scene has POV character'
                WHEN PrimaryLocationID IS NOT NULL THEN N'existing scene has location links'
                WHEN StartDateTime IS NOT NULL OR EndDateTime IS NOT NULL OR DurationAmount IS NOT NULL OR DurationUnitID IS NOT NULL OR NULLIF(LTRIM(RTRIM(ISNULL(RelativeTimeText, N''))), N'') IS NOT NULL THEN N'existing scene has time data'
                WHEN NULLIF(LTRIM(RTRIM(ISNULL(ScenePurposeNotes, N''))), N'') IS NOT NULL THEN N'existing scene has purpose notes'
                WHEN NULLIF(LTRIM(RTRIM(ISNULL(SceneOutcomeNotes, N''))), N'') IS NOT NULL THEN N'existing scene has outcome notes'
                WHEN ISNULL(FloorPlanID, 0) <> 0 OR ISNULL(InitialFloorPlanFloorID, 0) <> 0 THEN N'existing scene has floor plan links'
                WHEN NULLIF(LTRIM(RTRIM(ISNULL(ImportSource, N''))), N'') IS NOT NULL OR ImportRunID IS NOT NULL OR SourceStartParagraph IS NOT NULL OR SourceEndParagraph IS NOT NULL THEN N'existing scene has import source tracking'
                ELSE N'chapter contains existing authored scenes'
            END
        FROM dbo.Scenes
        WHERE SceneID = @SceneID;
    END;

    IF @CanCommit = 1 AND EXISTS
    (
        SELECT 1
        FROM dbo.SceneMetricValues smv
        INNER JOIN dbo.SceneMetricTypes smt ON smt.MetricTypeID = smv.MetricTypeID
        WHERE smv.SceneID = @SceneID
            AND (smv.Value <> smt.DefaultValue OR NULLIF(LTRIM(RTRIM(ISNULL(smv.Notes, N''))), N'') IS NOT NULL)
    )
    BEGIN
        SET @CanCommit = 0;
        SET @BlockReason = N'existing scene has edited metrics';
    END;

    IF @CanCommit = 1 AND EXISTS (SELECT 1 FROM dbo.SceneNotes WHERE SceneID = @SceneID)
    BEGIN SET @CanCommit = 0; SET @BlockReason = N'existing scene has user notes'; END;

    IF @CanCommit = 1 AND EXISTS (SELECT 1 FROM dbo.ScenePurposes WHERE SceneID = @SceneID)
    BEGIN SET @CanCommit = 0; SET @BlockReason = N'existing scene has purpose records'; END;

    IF @CanCommit = 1 AND EXISTS (SELECT 1 FROM dbo.SceneOutcomes WHERE SceneID = @SceneID)
    BEGIN SET @CanCommit = 0; SET @BlockReason = N'existing scene has outcome records'; END;

    IF @CanCommit = 1 AND EXISTS (SELECT 1 FROM dbo.SceneCharacters WHERE SceneID = @SceneID)
    BEGIN SET @CanCommit = 0; SET @BlockReason = N'existing scene has character appearances'; END;

    IF @CanCommit = 1 AND EXISTS (SELECT 1 FROM dbo.SceneAssetLocations WHERE SceneID = @SceneID)
    BEGIN SET @CanCommit = 0; SET @BlockReason = N'existing scene has asset links'; END;

    IF @CanCommit = 1 AND EXISTS (SELECT 1 FROM dbo.SceneFloorPlanOccupancy WHERE SceneID = @SceneID)
    BEGIN SET @CanCommit = 0; SET @BlockReason = N'existing scene has floor plan occupancy'; END;

    IF @CanCommit = 1 AND EXISTS (SELECT 1 FROM dbo.SceneDependencies WHERE IsArchived = 0 AND (SourceSceneID = @SceneID OR TargetSceneID = @SceneID))
    BEGIN SET @CanCommit = 0; SET @BlockReason = N'existing scene has dependency links'; END;

    IF @CanCommit = 1 AND EXISTS (SELECT 1 FROM dbo.SceneChecklistItems WHERE SceneID = @SceneID)
    BEGIN SET @CanCommit = 0; SET @BlockReason = N'existing scene has checklist items'; END;

    IF @CanCommit = 1 AND EXISTS (SELECT 1 FROM dbo.SceneAttachments WHERE SceneID = @SceneID)
    BEGIN SET @CanCommit = 0; SET @BlockReason = N'existing scene has attachments'; END;

    IF @CanCommit = 1 AND EXISTS (SELECT 1 FROM dbo.ThreadEvents WHERE SceneID = @SceneID)
    BEGIN SET @CanCommit = 0; SET @BlockReason = N'existing scene has thread events'; END;

    IF @CanCommit = 1 AND EXISTS (SELECT 1 FROM dbo.RelationshipEvents WHERE SceneID = @SceneID)
    BEGIN SET @CanCommit = 0; SET @BlockReason = N'existing scene has relationship events'; END;

    IF @CanCommit = 1 AND EXISTS (SELECT 1 FROM dbo.AssetEvents WHERE SceneID = @SceneID)
    BEGIN SET @CanCommit = 0; SET @BlockReason = N'existing scene has asset events'; END;

    IF @CanCommit = 1 AND EXISTS (SELECT 1 FROM dbo.AssetCustodyEvents WHERE SceneID = @SceneID)
    BEGIN SET @CanCommit = 0; SET @BlockReason = N'existing scene has custody events'; END;

    IF @CanCommit = 1 AND EXISTS (SELECT 1 FROM dbo.CharacterKnowledge WHERE SceneID = @SceneID)
    BEGIN SET @CanCommit = 0; SET @BlockReason = N'existing scene has knowledge records'; END;

    IF @CanCommit = 1 AND EXISTS (SELECT 1 FROM dbo.CharacterAttributeEvents WHERE SceneID = @SceneID)
    BEGIN SET @CanCommit = 0; SET @BlockReason = N'existing scene has character attribute events'; END;

    IF @CanCommit = 1 AND EXISTS (SELECT 1 FROM dbo.ContinuityWarnings WHERE SceneID = @SceneID AND IsDismissed = 0)
    BEGIN SET @CanCommit = 0; SET @BlockReason = N'existing scene has continuity warnings'; END;

    IF @CanCommit = 1 AND EXISTS (SELECT 1 FROM dbo.SceneCharacterSuggestions WHERE SceneID = @SceneID)
    BEGIN SET @CanCommit = 0; SET @BlockReason = N'existing scene has character suggestions'; END;

    IF @CanCommit = 1 AND EXISTS (SELECT 1 FROM dbo.SceneAssetSuggestions WHERE SceneID = @SceneID)
    BEGIN SET @CanCommit = 0; SET @BlockReason = N'existing scene has asset suggestions'; END;

    IF @CanCommit = 1 AND EXISTS (SELECT 1 FROM dbo.SceneLocationSuggestions WHERE SceneID = @SceneID)
    BEGIN SET @CanCommit = 0; SET @BlockReason = N'existing scene has location suggestions'; END;

    IF @CanCommit = 1 AND EXISTS
    (
        SELECT 1
        FROM dbo.SceneWorkflow
        WHERE SceneID = @SceneID
            AND
            (
                DraftStatus <> N'Planned'
                OR EstimatedWordCount IS NOT NULL
                OR ActualWordCount IS NOT NULL
                OR DraftedDate IS NOT NULL
                OR LastWorkedOn IS NOT NULL
                OR ReadyForDraft = 1
                OR ReadyForRevision = 1
                OR ReadyForPolish = 1
                OR IsBlocked = 1
                OR NULLIF(LTRIM(RTRIM(ISNULL(BlockedReason, N''))), N'') IS NOT NULL
                OR Priority IS NOT NULL
            )
    )
    BEGIN
        SET @CanCommit = 0;
        SET @BlockReason = N'existing scene has workflow data';
    END;

    IF @CanCommit = 1
    BEGIN
        SET @HasUntouchedDefaultPlaceholder = 1;
        SET @CommitMode = N'ReplaceDefaultPlaceholder';
        SET @BlockReason = NULL;
    END;

    SELECT @ActiveSceneCount AS ActiveSceneCount, @CanCommit AS CanCommit, @HasUntouchedDefaultPlaceholder AS HasUntouchedDefaultPlaceholder,
        CASE WHEN @HasUntouchedDefaultPlaceholder = 1 THEN @SceneID ELSE NULL END AS PlaceholderSceneID,
        @CommitMode AS CommitMode, @BlockReason AS BlockReason;
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'Scene'
    BEGIN
        SELECT @IsArchived = IsArchived FROM dbo.Scenes WHERE SceneID = @EntityID;
        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;

        BEGIN TRY
            BEGIN TRANSACTION;

            DELETE petpl
            FROM dbo.PlotEventTargetPlotLines petpl
            INNER JOIN dbo.ThreadEvents te ON te.ThreadEventID = petpl.PlotEventID
            WHERE te.SceneID = @EntityID;

            DELETE acec
            FROM dbo.AssetCustodyEventCharacters acec
            INNER JOIN dbo.AssetCustodyEvents ace ON ace.AssetCustodyEventID = acec.AssetCustodyEventID
            WHERE ace.SceneID = @EntityID;

            DELETE FROM dbo.ContinuityWarningAcknowledgements WHERE SceneID = @EntityID;

            DELETE FROM dbo.WordCompanionSceneAssets WHERE SceneID = @EntityID;
            DELETE FROM dbo.WordCompanionSceneLocations WHERE SceneID = @EntityID;
            DELETE FROM dbo.SceneCharacterSuggestions WHERE SceneID = @EntityID;
            DELETE FROM dbo.SceneAssetSuggestions WHERE SceneID = @EntityID;
            DELETE FROM dbo.SceneLocationSuggestions WHERE SceneID = @EntityID;
            DELETE FROM dbo.OnboardingManuscriptBuildSceneMap WHERE SceneID = @EntityID;
            DELETE FROM dbo.ScenarioSceneOrder WHERE SceneID = @EntityID;
            DELETE FROM dbo.ScenarioWarnings WHERE SceneID = @EntityID;
            DELETE FROM dbo.WritingScheduleItems WHERE SceneID = @EntityID;
            DELETE FROM dbo.SceneAttachments WHERE SceneID = @EntityID;
            DELETE FROM dbo.SceneChecklistItems WHERE SceneID = @EntityID;
            DELETE FROM dbo.SceneWorkflow WHERE SceneID = @EntityID;
            DELETE FROM dbo.SceneNotes WHERE SceneID = @EntityID;
            DELETE FROM dbo.SceneFloorPlanOccupancy WHERE SceneID = @EntityID;
            DELETE FROM dbo.SceneDependencies WHERE SourceSceneID = @EntityID OR TargetSceneID = @EntityID;
            DELETE FROM dbo.RelationshipEvents WHERE SceneID = @EntityID;
            DELETE FROM dbo.CharacterKnowledge WHERE SceneID = @EntityID;
            DELETE FROM dbo.CharacterAttributeEvents WHERE SceneID = @EntityID;
            DELETE FROM dbo.SceneCharacters WHERE SceneID = @EntityID;
            DELETE FROM dbo.AssetCustodyEvents WHERE SceneID = @EntityID;
            DELETE FROM dbo.AssetEvents WHERE SceneID = @EntityID;
            DELETE FROM dbo.ThreadEvents WHERE SceneID = @EntityID;
            DELETE FROM dbo.ContinuityWarnings WHERE SceneID = @EntityID;
            DELETE FROM dbo.SceneAssetLocations WHERE SceneID = @EntityID;
            DELETE FROM dbo.SceneMetricValues WHERE SceneID = @EntityID;
            DELETE FROM dbo.ScenePurposes WHERE SceneID = @EntityID;
            DELETE FROM dbo.SceneOutcomes WHERE SceneID = @EntityID;

            UPDATE dbo.Characters SET AgeReferenceSceneID = NULL WHERE AgeReferenceSceneID = @EntityID;
            UPDATE dbo.CharacterRelationships SET StartSceneID = NULL WHERE StartSceneID = @EntityID;
            UPDATE dbo.CharacterRelationships SET EndSceneID = NULL WHERE EndSceneID = @EntityID;
            UPDATE dbo.PlotThreads SET IntroducedSceneID = NULL WHERE IntroducedSceneID = @EntityID;
            UPDATE dbo.PlotThreads SET PlannedResolutionSceneID = NULL WHERE PlannedResolutionSceneID = @EntityID;
            UPDATE dbo.PlotThreads SET ActualResolutionSceneID = NULL WHERE ActualResolutionSceneID = @EntityID;

            DELETE FROM dbo.Scenes WHERE SceneID = @EntityID AND IsArchived = 1;

            COMMIT TRANSACTION;
            SELECT CAST(1 AS bit) AS Succeeded, N'Archived scene permanently deleted.' AS Message;
            RETURN;
        END TRY
        BEGIN CATCH
            IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION;
            SELECT CAST(0 AS bit) AS Succeeded, CONCAT(N'Archived scene could not be permanently deleted: ', ERROR_MESSAGE()) AS Message;
            RETURN;
        END CATCH;
    END;

    IF @EntityType = N'Book'
    BEGIN
        SELECT @IsArchived = IsArchived FROM dbo.Books WHERE BookID = @EntityID;
        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;

        BEGIN TRY
            BEGIN TRANSACTION;

            DECLARE @SceneIDs TABLE (SceneID int NOT NULL PRIMARY KEY);
            DECLARE @ChapterIDs TABLE (ChapterID int NOT NULL PRIMARY KEY);

            INSERT @ChapterIDs (ChapterID)
            SELECT ChapterID FROM dbo.Chapters WHERE BookID = @EntityID;

            INSERT @SceneIDs (SceneID)
            SELECT s.SceneID
            FROM dbo.Scenes s
            INNER JOIN @ChapterIDs c ON c.ChapterID = s.ChapterID;

            DELETE petpl
            FROM dbo.PlotEventTargetPlotLines petpl
            INNER JOIN dbo.ThreadEvents te ON te.ThreadEventID = petpl.PlotEventID
            INNER JOIN @SceneIDs scene ON scene.SceneID = te.SceneID;

            DELETE acec
            FROM dbo.AssetCustodyEventCharacters acec
            INNER JOIN dbo.AssetCustodyEvents ace ON ace.AssetCustodyEventID = acec.AssetCustodyEventID
            INNER JOIN @SceneIDs scene ON scene.SceneID = ace.SceneID;

            DELETE cwa
            FROM dbo.ContinuityWarningAcknowledgements cwa
            INNER JOIN @SceneIDs scene ON scene.SceneID = cwa.SceneID;

            DELETE wcsa FROM dbo.WordCompanionSceneAssets wcsa INNER JOIN @SceneIDs scene ON scene.SceneID = wcsa.SceneID;
            DELETE wcsl FROM dbo.WordCompanionSceneLocations wcsl INNER JOIN @SceneIDs scene ON scene.SceneID = wcsl.SceneID;
            DELETE scs FROM dbo.SceneCharacterSuggestions scs INNER JOIN @SceneIDs scene ON scene.SceneID = scs.SceneID;
            DELETE sas FROM dbo.SceneAssetSuggestions sas INNER JOIN @SceneIDs scene ON scene.SceneID = sas.SceneID;
            DELETE sls FROM dbo.SceneLocationSuggestions sls INNER JOIN @SceneIDs scene ON scene.SceneID = sls.SceneID;
            DELETE ombsm FROM dbo.OnboardingManuscriptBuildSceneMap ombsm INNER JOIN @SceneIDs scene ON scene.SceneID = ombsm.SceneID;
            DELETE ombcm FROM dbo.OnboardingManuscriptBuildChapterMap ombcm INNER JOIN @ChapterIDs c ON c.ChapterID = ombcm.ChapterID;
            DELETE sso FROM dbo.ScenarioSceneOrder sso WHERE EXISTS (SELECT 1 FROM @SceneIDs scene WHERE scene.SceneID = sso.SceneID) OR EXISTS (SELECT 1 FROM @ChapterIDs c WHERE c.ChapterID = sso.ProposedChapterID);
            DELETE sw FROM dbo.ScenarioWarnings sw INNER JOIN @SceneIDs scene ON scene.SceneID = sw.SceneID;
            DELETE wsi FROM dbo.WritingScheduleItems wsi INNER JOIN @SceneIDs scene ON scene.SceneID = wsi.SceneID;
            DELETE sa FROM dbo.SceneAttachments sa INNER JOIN @SceneIDs scene ON scene.SceneID = sa.SceneID;
            DELETE sci FROM dbo.SceneChecklistItems sci INNER JOIN @SceneIDs scene ON scene.SceneID = sci.SceneID;
            DELETE swf FROM dbo.SceneWorkflow swf INNER JOIN @SceneIDs scene ON scene.SceneID = swf.SceneID;
            DELETE sn FROM dbo.SceneNotes sn INNER JOIN @SceneIDs scene ON scene.SceneID = sn.SceneID;
            DELETE sfpo FROM dbo.SceneFloorPlanOccupancy sfpo INNER JOIN @SceneIDs scene ON scene.SceneID = sfpo.SceneID;
            DELETE sd FROM dbo.SceneDependencies sd WHERE EXISTS (SELECT 1 FROM @SceneIDs scene WHERE scene.SceneID = sd.SourceSceneID OR scene.SceneID = sd.TargetSceneID);
            DELETE re FROM dbo.RelationshipEvents re INNER JOIN @SceneIDs scene ON scene.SceneID = re.SceneID;
            DELETE ck FROM dbo.CharacterKnowledge ck INNER JOIN @SceneIDs scene ON scene.SceneID = ck.SceneID;
            DELETE cae FROM dbo.CharacterAttributeEvents cae INNER JOIN @SceneIDs scene ON scene.SceneID = cae.SceneID;
            DELETE sc FROM dbo.SceneCharacters sc INNER JOIN @SceneIDs scene ON scene.SceneID = sc.SceneID;
            DELETE ace FROM dbo.AssetCustodyEvents ace INNER JOIN @SceneIDs scene ON scene.SceneID = ace.SceneID;
            DELETE ae FROM dbo.AssetEvents ae INNER JOIN @SceneIDs scene ON scene.SceneID = ae.SceneID;
            DELETE te FROM dbo.ThreadEvents te INNER JOIN @SceneIDs scene ON scene.SceneID = te.SceneID;
            DELETE cw FROM dbo.ContinuityWarnings cw WHERE cw.BookID = @EntityID OR EXISTS (SELECT 1 FROM @ChapterIDs c WHERE c.ChapterID = cw.ChapterID) OR EXISTS (SELECT 1 FROM @SceneIDs s WHERE s.SceneID = cw.SceneID);
            DELETE sal FROM dbo.SceneAssetLocations sal INNER JOIN @SceneIDs scene ON scene.SceneID = sal.SceneID;
            DELETE smv FROM dbo.SceneMetricValues smv INNER JOIN @SceneIDs scene ON scene.SceneID = smv.SceneID;
            DELETE sp FROM dbo.ScenePurposes sp INNER JOIN @SceneIDs scene ON scene.SceneID = sp.SceneID;
            DELETE so FROM dbo.SceneOutcomes so INNER JOIN @SceneIDs scene ON scene.SceneID = so.SceneID;
            DELETE cg FROM dbo.ChapterGoals cg INNER JOIN @ChapterIDs c ON c.ChapterID = cg.ChapterID;

            UPDATE ch SET AgeReferenceSceneID = NULL FROM dbo.Characters ch INNER JOIN @SceneIDs scene ON scene.SceneID = ch.AgeReferenceSceneID;
            UPDATE cr SET StartSceneID = NULL FROM dbo.CharacterRelationships cr INNER JOIN @SceneIDs scene ON scene.SceneID = cr.StartSceneID;
            UPDATE cr SET EndSceneID = NULL FROM dbo.CharacterRelationships cr INNER JOIN @SceneIDs scene ON scene.SceneID = cr.EndSceneID;
            UPDATE pt SET IntroducedSceneID = NULL FROM dbo.PlotThreads pt INNER JOIN @SceneIDs scene ON scene.SceneID = pt.IntroducedSceneID;
            UPDATE pt SET PlannedResolutionSceneID = NULL FROM dbo.PlotThreads pt INNER JOIN @SceneIDs scene ON scene.SceneID = pt.PlannedResolutionSceneID;
            UPDATE pt SET ActualResolutionSceneID = NULL FROM dbo.PlotThreads pt INNER JOIN @SceneIDs scene ON scene.SceneID = pt.ActualResolutionSceneID;
            UPDATE cr SET InitialBookID = NULL FROM dbo.CharacterRelationships cr WHERE cr.InitialBookID = @EntityID;
            UPDATE pl SET BookID = NULL FROM dbo.PlotLines pl WHERE pl.BookID = @EntityID;
            UPDATE sc SET BookID = NULL FROM dbo.Scenarios sc WHERE sc.BookID = @EntityID;
            UPDATE tvp SET BookID = NULL FROM dbo.TimelineViewPresets tvp WHERE tvp.BookID = @EntityID;
            UPDATE vr SET BookID = NULL FROM dbo.ValidationRuns vr WHERE vr.BookID = @EntityID;
            UPDATE wp SET BookID = NULL FROM dbo.WritingPlans wp WHERE wp.BookID = @EntityID;
            UPDATE uos SET BookID = NULL FROM dbo.UserOnboardingState uos WHERE uos.BookID = @EntityID;
            UPDATE sir SET ChapterID = NULL FROM dbo.StoryIntelligenceRuns sir WHERE EXISTS (SELECT 1 FROM @ChapterIDs c WHERE c.ChapterID = sir.ChapterID);
            UPDATE sic SET BookID = NULL, ChapterID = NULL FROM dbo.StoryIntelligenceImportCommits sic WHERE sic.BookID = @EntityID OR EXISTS (SELECT 1 FROM @ChapterIDs c WHERE c.ChapterID = sic.ChapterID);

            DELETE FROM dbo.StoryIntelligenceJobs WHERE BookID = @EntityID;
            DELETE FROM dbo.StoryIntelligenceConsents WHERE BookID = @EntityID;
            DELETE FROM dbo.OnboardingManuscriptBuilds WHERE BookID = @EntityID;
            DELETE FROM dbo.ManuscriptDocuments WHERE BookID = @EntityID;
            DELETE s FROM dbo.Scenes s INNER JOIN @SceneIDs scene ON scene.SceneID = s.SceneID;
            DELETE c FROM dbo.Chapters c INNER JOIN @ChapterIDs chapter ON chapter.ChapterID = c.ChapterID;
            DELETE FROM dbo.Books WHERE BookID = @EntityID AND IsArchived = 1;

            COMMIT TRANSACTION;
            SELECT CAST(1 AS bit) AS Succeeded, N'Archived book permanently deleted.' AS Message;
            RETURN;
        END TRY
        BEGIN CATCH
            IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION;
            SELECT CAST(0 AS bit) AS Succeeded, CONCAT(N'Archived book could not be permanently deleted: ', ERROR_MESSAGE()) AS Message;
            RETURN;
        END CATCH;
    END;

    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'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'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
