IF OBJECT_ID(N'dbo.UserOnboardingState', N'U') IS NULL
BEGIN
    CREATE TABLE dbo.UserOnboardingState
    (
        UserOnboardingStateID int IDENTITY(1,1) NOT NULL CONSTRAINT PK_UserOnboardingState PRIMARY KEY,
        UserID int NOT NULL,
        OnboardingStartedUtc datetime2 NOT NULL CONSTRAINT DF_UserOnboardingState_Started DEFAULT SYSUTCDATETIME(),
        OnboardingCompletedUtc datetime2 NULL,
        CurrentStep nvarchar(50) NOT NULL CONSTRAINT DF_UserOnboardingState_CurrentStep DEFAULT N'Welcome',
        WritingJourney nvarchar(50) NULL,
        WritingSoftware nvarchar(50) NULL,
        UsesWordCompanion bit NULL,
        CreatedUtc datetime2 NOT NULL CONSTRAINT DF_UserOnboardingState_Created DEFAULT SYSUTCDATETIME(),
        UpdatedUtc datetime2 NOT NULL CONSTRAINT DF_UserOnboardingState_Updated DEFAULT SYSUTCDATETIME(),
        CONSTRAINT FK_UserOnboardingState_AppUser FOREIGN KEY (UserID) REFERENCES dbo.AppUser(UserID),
        CONSTRAINT CK_UserOnboardingState_CurrentStep CHECK (CurrentStep IN (N'Welcome', N'WritingJourney', N'WritingSoftware', N'Complete')),
        CONSTRAINT CK_UserOnboardingState_WritingJourney CHECK (WritingJourney IS NULL OR WritingJourney IN (N'PlanningNewStory', N'AlreadyStarted', N'ManuscriptMostlyComplete')),
        CONSTRAINT CK_UserOnboardingState_WritingSoftware CHECK (WritingSoftware IS NULL OR WritingSoftware IN (N'MicrosoftWord', N'GoogleDocs', N'Scrivener', N'LibreOfficeOpenOffice', N'MarkdownObsidian', N'Other'))
    );
END;

IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'UX_UserOnboardingState_UserID' AND object_id = OBJECT_ID(N'dbo.UserOnboardingState'))
    CREATE UNIQUE INDEX UX_UserOnboardingState_UserID ON dbo.UserOnboardingState(UserID);
GO

CREATE OR ALTER PROCEDURE dbo.UserOnboarding_Get
    @UserID int
AS
BEGIN
    SET NOCOUNT ON;

    SELECT UserOnboardingStateID, UserID, OnboardingStartedUtc, OnboardingCompletedUtc,
        CurrentStep, WritingJourney, WritingSoftware, UsesWordCompanion, CreatedUtc, UpdatedUtc
    FROM dbo.UserOnboardingState
    WHERE UserID = @UserID;
END;
GO

CREATE OR ALTER PROCEDURE dbo.UserOnboarding_GetOrCreate
    @UserID int
AS
BEGIN
    SET NOCOUNT ON;

    IF NOT EXISTS (SELECT 1 FROM dbo.UserOnboardingState WHERE UserID = @UserID)
    BEGIN
        INSERT INTO dbo.UserOnboardingState (UserID)
        VALUES (@UserID);
    END;

    EXEC dbo.UserOnboarding_Get @UserID = @UserID;
END;
GO

CREATE OR ALTER PROCEDURE dbo.UserOnboarding_SetCurrentStep
    @UserID int,
    @CurrentStep nvarchar(50)
AS
BEGIN
    SET NOCOUNT ON;

    IF NOT EXISTS (SELECT 1 FROM dbo.UserOnboardingState WHERE UserID = @UserID)
    BEGIN
        INSERT INTO dbo.UserOnboardingState (UserID)
        VALUES (@UserID);
    END;

    UPDATE dbo.UserOnboardingState
    SET CurrentStep = @CurrentStep,
        OnboardingCompletedUtc = CASE WHEN @CurrentStep = N'Complete' THEN COALESCE(OnboardingCompletedUtc, SYSUTCDATETIME()) ELSE NULL END,
        UpdatedUtc = SYSUTCDATETIME()
    WHERE UserID = @UserID;

    EXEC dbo.UserOnboarding_Get @UserID = @UserID;
END;
GO

CREATE OR ALTER PROCEDURE dbo.UserOnboarding_SaveWritingJourney
    @UserID int,
    @WritingJourney nvarchar(50)
AS
BEGIN
    SET NOCOUNT ON;

    IF NOT EXISTS (SELECT 1 FROM dbo.UserOnboardingState WHERE UserID = @UserID)
    BEGIN
        INSERT INTO dbo.UserOnboardingState (UserID)
        VALUES (@UserID);
    END;

    UPDATE dbo.UserOnboardingState
    SET WritingJourney = @WritingJourney,
        CurrentStep = N'WritingSoftware',
        UpdatedUtc = SYSUTCDATETIME()
    WHERE UserID = @UserID;

    EXEC dbo.UserOnboarding_Get @UserID = @UserID;
END;
GO

CREATE OR ALTER PROCEDURE dbo.UserOnboarding_SaveWritingSoftware
    @UserID int,
    @WritingSoftware nvarchar(50)
AS
BEGIN
    SET NOCOUNT ON;

    IF NOT EXISTS (SELECT 1 FROM dbo.UserOnboardingState WHERE UserID = @UserID)
    BEGIN
        INSERT INTO dbo.UserOnboardingState (UserID)
        VALUES (@UserID);
    END;

    UPDATE dbo.UserOnboardingState
    SET WritingSoftware = @WritingSoftware,
        UsesWordCompanion = CASE WHEN @WritingSoftware = N'MicrosoftWord' THEN 1 ELSE 0 END,
        CurrentStep = N'Complete',
        OnboardingCompletedUtc = COALESCE(OnboardingCompletedUtc, SYSUTCDATETIME()),
        UpdatedUtc = SYSUTCDATETIME()
    WHERE UserID = @UserID;

    EXEC dbo.UserOnboarding_Get @UserID = @UserID;
END;
GO

CREATE OR ALTER PROCEDURE dbo.UserOnboarding_MarkCompleted
    @UserID int
AS
BEGIN
    SET NOCOUNT ON;

    IF NOT EXISTS (SELECT 1 FROM dbo.UserOnboardingState WHERE UserID = @UserID)
    BEGIN
        INSERT INTO dbo.UserOnboardingState (UserID)
        VALUES (@UserID);
    END;

    UPDATE dbo.UserOnboardingState
    SET CurrentStep = N'Complete',
        OnboardingCompletedUtc = COALESCE(OnboardingCompletedUtc, SYSUTCDATETIME()),
        UpdatedUtc = SYSUTCDATETIME()
    WHERE UserID = @UserID;

    EXEC dbo.UserOnboarding_Get @UserID = @UserID;
END;
GO

CREATE OR ALTER PROCEDURE dbo.UserOnboarding_ShouldShowWordCompanionHeader
    @UserID int
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @HasWordPreference bit = 0;
    DECLARE @HasCompanionUsage bit = 0;

    IF EXISTS
    (
        SELECT 1
        FROM dbo.UserOnboardingState
        WHERE UserID = @UserID
            AND WritingSoftware = N'MicrosoftWord'
            AND UsesWordCompanion = 1
    )
        SET @HasWordPreference = 1;

    IF OBJECT_ID(N'dbo.ManuscriptDocuments', N'U') IS NOT NULL
        AND EXISTS
        (
            SELECT 1
            FROM dbo.ManuscriptDocuments md
            LEFT JOIN dbo.ProjectUserAccess pua ON pua.ProjectID = md.ProjectID
                AND pua.UserID = @UserID
                AND pua.IsActive = 1
            WHERE md.IsActive = 1
                AND (md.CreatedByUserID = @UserID OR pua.ProjectUserAccessID IS NOT NULL)
        )
        SET @HasCompanionUsage = 1;

    SELECT CAST(CASE WHEN @HasWordPreference = 1 OR @HasCompanionUsage = 1 THEN 1 ELSE 0 END AS bit);
END;
GO
