DECLARE @constraintName sysname;

SELECT @constraintName = dc.name
FROM sys.default_constraints dc
INNER JOIN sys.columns c ON c.default_object_id = dc.object_id
INNER JOIN sys.tables t ON t.object_id = c.object_id
INNER JOIN sys.schemas s ON s.schema_id = t.schema_id
WHERE s.name = N'dbo'
  AND t.name = N'ProjectTimelineSettings'
  AND c.name = N'ShowStoryAssets';

IF @constraintName IS NOT NULL
BEGIN
    EXEC(N'ALTER TABLE dbo.ProjectTimelineSettings DROP CONSTRAINT ' + QUOTENAME(@constraintName));
END;

IF COL_LENGTH(N'dbo.ProjectTimelineSettings', N'ShowStoryAssets') IS NOT NULL
BEGIN
    ALTER TABLE dbo.ProjectTimelineSettings
        ADD CONSTRAINT DF_ProjectTimelineSettings_ShowStoryAssets DEFAULT 0 FOR ShowStoryAssets;
END;
GO

DECLARE @constraintName sysname;

SELECT @constraintName = dc.name
FROM sys.default_constraints dc
INNER JOIN sys.columns c ON c.default_object_id = dc.object_id
INNER JOIN sys.tables t ON t.object_id = c.object_id
INNER JOIN sys.schemas s ON s.schema_id = t.schema_id
WHERE s.name = N'dbo'
  AND t.name = N'ProjectTimelineSettings'
  AND c.name = N'ShowCharacterAppearances';

IF @constraintName IS NOT NULL
BEGIN
    EXEC(N'ALTER TABLE dbo.ProjectTimelineSettings DROP CONSTRAINT ' + QUOTENAME(@constraintName));
END;

IF COL_LENGTH(N'dbo.ProjectTimelineSettings', N'ShowCharacterAppearances') IS NOT NULL
BEGIN
    ALTER TABLE dbo.ProjectTimelineSettings
        ADD CONSTRAINT DF_ProjectTimelineSettings_ShowCharacterAppearances DEFAULT 0 FOR ShowCharacterAppearances;
END;
GO

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

    IF NOT EXISTS (SELECT 1 FROM dbo.ProjectTimelineSettings WHERE ProjectID = @ProjectID)
    BEGIN
        INSERT dbo.ProjectTimelineSettings
            (ProjectID, ShowSceneCards, ShowMetricShape, ShowPlotLines, ShowStoryAssets, ShowCharacterAppearances, ShowWarnings)
        VALUES
            (@ProjectID, 1, 1, 1, 0, 0, 1);
    END
END;
GO
