IF OBJECT_ID('dbo.RagChunks', 'U') IS NULL
BEGIN
    CREATE TABLE dbo.RagChunks (
        Id NVARCHAR(64) NOT NULL CONSTRAINT PK_RagChunks PRIMARY KEY,
        DocumentId NVARCHAR(64) NOT NULL,
        ChunkIndex INT NOT NULL,
        Text NVARCHAR(MAX) NOT NULL,
        Embedding VARBINARY(MAX) NOT NULL
    );
END
GO

IF OBJECT_ID('dbo.RagDocuments', 'U') IS NULL
BEGIN
    CREATE TABLE dbo.RagDocuments (
        Id NVARCHAR(64) NOT NULL CONSTRAINT PK_RagDocuments PRIMARY KEY,
        DocumentType NVARCHAR(80) NOT NULL,
        Title NVARCHAR(300) NOT NULL,
        SourceUrl NVARCHAR(1200) NULL,
        RawText NVARCHAR(MAX) NOT NULL,
        TextHash NVARCHAR(64) NOT NULL,
        TypeConfidence FLOAT NOT NULL,
        MetadataJson NVARCHAR(MAX) NOT NULL CONSTRAINT DF_RagDocuments_MetadataJson DEFAULT '{}',
        CreatedAt DATETIME2 NOT NULL CONSTRAINT DF_RagDocuments_CreatedAt DEFAULT SYSUTCDATETIME()
    );

    CREATE INDEX IX_RagDocuments_TextHash ON dbo.RagDocuments(TextHash);
    CREATE INDEX IX_RagDocuments_DocumentType ON dbo.RagDocuments(DocumentType);
END
GO

IF NOT EXISTS (SELECT 1 FROM sys.foreign_keys WHERE name = 'FK_RagChunks_RagDocuments')
BEGIN
    ALTER TABLE dbo.RagChunks
    ADD CONSTRAINT FK_RagChunks_RagDocuments FOREIGN KEY (DocumentId) REFERENCES dbo.RagDocuments(Id) ON DELETE CASCADE;
END
GO

IF OBJECT_ID('dbo.RagEmbeddingCache', 'U') IS NULL
BEGIN
    CREATE TABLE dbo.RagEmbeddingCache (
        CacheKey NVARCHAR(64) NOT NULL CONSTRAINT PK_RagEmbeddingCache PRIMARY KEY,
        Model NVARCHAR(120) NOT NULL,
        TextHash NVARCHAR(64) NOT NULL,
        Vector VARBINARY(MAX) NOT NULL,
        CreatedAt DATETIME2 NOT NULL CONSTRAINT DF_RagEmbeddingCache_CreatedAt DEFAULT SYSUTCDATETIME()
    );

    CREATE INDEX IX_RagEmbeddingCache_TextHash ON dbo.RagEmbeddingCache(TextHash);
END
GO

IF OBJECT_ID('dbo.RagChatCompletionCache', 'U') IS NULL
BEGIN
    CREATE TABLE dbo.RagChatCompletionCache (
        CacheKey NVARCHAR(64) NOT NULL CONSTRAINT PK_RagChatCompletionCache PRIMARY KEY,
        Model NVARCHAR(120) NOT NULL,
        Temperature DECIMAL(4,2) NOT NULL,
        ResponseText NVARCHAR(MAX) NOT NULL,
        CreatedAt DATETIME2 NOT NULL CONSTRAINT DF_RagChatCompletionCache_CreatedAt DEFAULT SYSUTCDATETIME()
    );
END
GO
