-- LLM / 知识库 / 企微 AI 字段

CREATE TABLE IF NOT EXISTS `llm_api_config` (
  `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(64) NOT NULL,
  `provider` VARCHAR(32) NOT NULL,
  `base_url` VARCHAR(512) NOT NULL,
  `api_key` VARCHAR(512) NOT NULL,
  `model_name` VARCHAR(128) NOT NULL,
  `temperature` DECIMAL(3, 2) NULL,
  `max_tokens` INT NULL,
  `system_prompt` TEXT NULL,
  `enabled` TINYINT(1) NOT NULL DEFAULT 1,
  `created_by_hq_account_id` BIGINT UNSIGNED NOT NULL,
  `created_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
  `updated_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
  PRIMARY KEY (`id`),
  INDEX `llm_api_config_created_by_hq_account_id_enabled_idx` (`created_by_hq_account_id`, `enabled`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS `knowledge_base` (
  `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(128) NOT NULL,
  `description` VARCHAR(512) NULL,
  `enabled` TINYINT(1) NOT NULL DEFAULT 1,
  `created_by_hq_account_id` BIGINT UNSIGNED NOT NULL,
  `created_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
  `updated_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
  PRIMARY KEY (`id`),
  INDEX `knowledge_base_created_by_hq_account_id_enabled_idx` (`created_by_hq_account_id`, `enabled`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS `knowledge_document` (
  `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  `knowledge_base_id` BIGINT UNSIGNED NOT NULL,
  `title` VARCHAR(256) NOT NULL,
  `file_name` VARCHAR(256) NULL,
  `file_url` VARCHAR(1024) NULL,
  `mime_type` VARCHAR(128) NULL,
  `size_bytes` INT NULL,
  `content_text` LONGTEXT NULL,
  `status` VARCHAR(16) NOT NULL DEFAULT 'READY',
  `error_message` VARCHAR(512) NULL,
  `created_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
  `updated_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
  PRIMARY KEY (`id`),
  INDEX `knowledge_document_knowledge_base_id_idx` (`knowledge_base_id`),
  CONSTRAINT `knowledge_document_knowledge_base_id_fkey`
    FOREIGN KEY (`knowledge_base_id`) REFERENCES `knowledge_base` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
