USE [RobotInstaller];
GO

SET ANSI_NULLS ON;
SET QUOTED_IDENTIFIER ON;
GO

IF OBJECT_ID(N'dbo.Documents', N'U') IS NULL
BEGIN
    CREATE TABLE dbo.Documents
    (
        Id UNIQUEIDENTIFIER NOT NULL
            CONSTRAINT PK_Documents PRIMARY KEY CLUSTERED
            CONSTRAINT DF_Documents_Id DEFAULT NEWSEQUENTIALID(),
        Title NVARCHAR(200) NOT NULL,
        Category NVARCHAR(50) NOT NULL
            CONSTRAINT DF_Documents_Category DEFAULT N'other',
        Summary NVARCHAR(1000) NULL,
        Content NVARCHAR(MAX) NULL,
        FilePath NVARCHAR(1000) NULL,
        OriginalFileName NVARCHAR(260) NULL,
        MimeType NVARCHAR(200) NULL,
        FileSizeBytes BIGINT NULL,
        CreatedByUserId UNIQUEIDENTIFIER NOT NULL,
        CreatedAt DATETIME2(3) NOT NULL
            CONSTRAINT DF_Documents_CreatedAt DEFAULT SYSUTCDATETIME(),
        UpdatedAt DATETIME2(3) NULL,
        CONSTRAINT FK_Documents_CreatedByUser
            FOREIGN KEY (CreatedByUserId) REFERENCES dbo.Users(Id),
        CONSTRAINT CK_Documents_Title_NotBlank CHECK (LEN(LTRIM(RTRIM(Title))) > 0),
        CONSTRAINT CK_Documents_Category CHECK (
            Category IN (N'introduction', N'guide', N'user-guide', N'technical', N'policy', N'other')
        ),
        CONSTRAINT CK_Documents_FileSizeBytes CHECK (FileSizeBytes IS NULL OR FileSizeBytes >= 0),
        CONSTRAINT CK_Documents_HasReadableContent CHECK (
            NULLIF(LTRIM(RTRIM(Content)), N'') IS NOT NULL OR FilePath IS NOT NULL
        )
    );
END;
GO

IF NOT EXISTS (
    SELECT 1
    FROM sys.indexes
    WHERE name = N'IX_Documents_Category_UpdatedAt'
      AND object_id = OBJECT_ID(N'dbo.Documents')
)
BEGIN
    CREATE INDEX IX_Documents_Category_UpdatedAt
    ON dbo.Documents(Category, UpdatedAt DESC, CreatedAt DESC);
END;
GO

IF NOT EXISTS (
    SELECT 1
    FROM sys.indexes
    WHERE name = N'IX_Documents_CreatedByUserId'
      AND object_id = OBJECT_ID(N'dbo.Documents')
)
BEGIN
    CREATE INDEX IX_Documents_CreatedByUserId
    ON dbo.Documents(CreatedByUserId);
END;
GO

PRINT N'RobotInstaller documents schema is ready.';
GO
