-- Add knowledge_config field to prompt_templates
ALTER TABLE "capability_schema"."prompt_templates" ADD COLUMN "knowledge_config" JSONB;

-- CreateTable: system_knowledge_bases
CREATE TABLE "capability_schema"."system_knowledge_bases" (
    "id" TEXT NOT NULL,
    "code" VARCHAR(50) NOT NULL,
    "name" VARCHAR(100) NOT NULL,
    "description" TEXT,
    "category" VARCHAR(50),
    "document_count" INTEGER NOT NULL DEFAULT 0,
    "total_tokens" INTEGER NOT NULL DEFAULT 0,
    "status" VARCHAR(20) NOT NULL DEFAULT 'active',
    "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updated_at" TIMESTAMP(3) NOT NULL,

    CONSTRAINT "system_knowledge_bases_pkey" PRIMARY KEY ("id")
);

-- CreateTable: system_kb_documents
CREATE TABLE "capability_schema"."system_kb_documents" (
    "id" TEXT NOT NULL,
    "kb_id" TEXT NOT NULL,
    "filename" VARCHAR(255) NOT NULL,
    "file_path" VARCHAR(500),
    "file_size" INTEGER,
    "file_type" VARCHAR(50),
    "content" TEXT,
    "token_count" INTEGER NOT NULL DEFAULT 0,
    "status" VARCHAR(20) NOT NULL DEFAULT 'pending',
    "error_message" TEXT,
    "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updated_at" TIMESTAMP(3) NOT NULL,

    CONSTRAINT "system_kb_documents_pkey" PRIMARY KEY ("id")
);

-- CreateIndex
CREATE UNIQUE INDEX "system_knowledge_bases_code_key" ON "capability_schema"."system_knowledge_bases"("code");

-- CreateIndex
CREATE INDEX "idx_system_kb_category" ON "capability_schema"."system_knowledge_bases"("category");

-- CreateIndex
CREATE INDEX "idx_system_kb_status" ON "capability_schema"."system_knowledge_bases"("status");

-- CreateIndex
CREATE INDEX "idx_system_kb_docs_kb_id" ON "capability_schema"."system_kb_documents"("kb_id");

-- CreateIndex
CREATE INDEX "idx_system_kb_docs_status" ON "capability_schema"."system_kb_documents"("status");

-- AddForeignKey
ALTER TABLE "capability_schema"."system_kb_documents" ADD CONSTRAINT "system_kb_documents_kb_id_fkey" FOREIGN KEY ("kb_id") REFERENCES "capability_schema"."system_knowledge_bases"("id") ON DELETE CASCADE ON UPDATE CASCADE;
