SET NAMES utf8mb4;

INSERT INTO `tb_sys_api_key_resource` (`id`, `request_interface`, `title`)
VALUES
    (366700000000000101, '/public-api/knowledge-share/detail', '知识库读取'),
    (366700000000000102, '/public-api/knowledge-share/search', '知识库读取'),
    (366700000000000103, '/public-api/knowledge-share/document/page', '知识库读取'),
    (366700000000000104, '/public-api/knowledge-share/document/download', '知识库读取'),
    (366700000000000105, '/public-api/knowledge-share/documentChunk/page', '知识库读取'),
    (366700000000000106, '/public-api/knowledge-share/faq/page', '知识库读取'),
    (366700000000000107, '/public-api/knowledge-share/faq/detail', '知识库读取'),
    (366700000000000108, '/public-api/knowledge-share/faq/exportExcel', '知识库读取'),
    (366700000000000109, '/public-api/knowledge-share/document/import/batch', '知识导入'),
    (366700000000000110, '/public-api/knowledge-share/document/import/batch/status', '知识导入'),
    (366700000000000111, '/public-api/knowledge-share/document/import/batch/retry', '知识导入'),
    (366700000000000112, '/public-api/knowledge-share/document/import/analyze', '知识导入'),
    (366700000000000113, '/public-api/knowledge-share/document/import/preview', '知识导入'),
    (366700000000000114, '/public-api/knowledge-share/document/import/commit', '知识导入'),
    (366700000000000115, '/public-api/knowledge-share/document/import/task/create', '知识导入'),
    (366700000000000116, '/public-api/knowledge-share/document/import/task/detail', '知识导入'),
    (366700000000000117, '/public-api/knowledge-share/document/import/task/preview', '知识导入'),
    (366700000000000118, '/public-api/knowledge-share/document/import/task/startIndex', '知识导入'),
    (366700000000000119, '/public-api/knowledge-share/document/import/task/retryParse', '知识导入'),
    (366700000000000120, '/public-api/knowledge-share/document/import/task/retryIndex', '知识导入'),
    (366700000000000121, '/public-api/knowledge-share/faq/importExcel', '知识导入'),
    (366700000000000122, '/public-api/knowledge-share/faq/downloadImportTemplate', '知识导入'),
    (366700000000000123, '/public-api/knowledge-share/document/remove', '知识库维护'),
    (366700000000000124, '/public-api/knowledge-share/documentChunk/update', '知识库维护'),
    (366700000000000125, '/public-api/knowledge-share/documentChunk/remove', '知识库维护'),
    (366700000000000126, '/public-api/knowledge-share/faq/save', '知识库维护'),
    (366700000000000127, '/public-api/knowledge-share/faq/update', '知识库维护'),
    (366700000000000128, '/public-api/knowledge-share/faq/remove', '知识库维护')
ON DUPLICATE KEY UPDATE `title` = VALUES(`title`);

SET @migrated_knowledge_api_key_count = (
    SELECT COUNT(DISTINCT mapping.`api_key_id`)
    FROM `tb_sys_api_key_resource_mapping` mapping
    WHERE mapping.`resource_type` = 'KNOWLEDGE'
      AND mapping.`resource_target_id` IS NULL
);

UPDATE `tb_sys_api_key_resource_mapping` mapping
JOIN `tb_sys_api_key_resource` resource
  ON resource.`id` = mapping.`api_key_resource_id`
SET mapping.`action_scope` = CASE
    WHEN resource.`request_interface` IN (
        '/public-api/knowledge-share/detail',
        '/public-api/knowledge-share/search',
        '/public-api/knowledge-share/document/page',
        '/public-api/knowledge-share/document/download',
        '/public-api/knowledge-share/documentChunk/page',
        '/public-api/knowledge-share/faq/page',
        '/public-api/knowledge-share/faq/detail',
        '/public-api/knowledge-share/faq/exportExcel'
    ) THEN 'KNOWLEDGE_READ'
    WHEN resource.`request_interface` IN (
        '/public-api/knowledge-share/document/import/analyze',
        '/public-api/knowledge-share/document/import/preview',
        '/public-api/knowledge-share/document/import/commit',
        '/public-api/knowledge-share/document/import/task/create',
        '/public-api/knowledge-share/document/import/task/detail',
        '/public-api/knowledge-share/document/import/task/preview',
        '/public-api/knowledge-share/document/import/task/startIndex',
        '/public-api/knowledge-share/document/import/task/retryParse',
        '/public-api/knowledge-share/document/import/task/retryIndex',
        '/public-api/knowledge-share/faq/importExcel',
        '/public-api/knowledge-share/faq/downloadImportTemplate'
    ) THEN 'KNOWLEDGE_IMPORT'
    WHEN resource.`request_interface` IN (
        '/public-api/knowledge-share/document/remove',
        '/public-api/knowledge-share/documentChunk/update',
        '/public-api/knowledge-share/documentChunk/remove',
        '/public-api/knowledge-share/faq/save',
        '/public-api/knowledge-share/faq/update',
        '/public-api/knowledge-share/faq/remove'
    ) THEN 'KNOWLEDGE_MAINTENANCE'
    ELSE mapping.`action_scope`
END
WHERE mapping.`resource_type` = 'KNOWLEDGE';

SET @revoked_maintenance_mapping_count = (
    SELECT COUNT(*)
    FROM `tb_sys_api_key_resource_mapping`
    WHERE `resource_type` = 'KNOWLEDGE'
      AND `resource_target_id` IS NULL
      AND `action_scope` = 'KNOWLEDGE_MAINTENANCE'
);

DELETE FROM `tb_sys_api_key_resource_mapping`
WHERE `resource_type` = 'KNOWLEDGE'
  AND `resource_target_id` IS NULL
  AND `action_scope` = 'KNOWLEDGE_MAINTENANCE';

INSERT INTO `tb_sys_api_key_resource_mapping`
    (`id`, `api_key_id`, `api_key_resource_id`, `resource_type`,
     `resource_target_id`, `action_scope`)
SELECT
    CAST(
        366900000000000000
        + ROW_NUMBER() OVER (
            ORDER BY token.`api_key_id`,
                     COALESCE(token.`resource_target_id`, 0),
                     resource.`id`
        )
        AS UNSIGNED
    ),
    token.`api_key_id`,
    resource.`id`,
    'KNOWLEDGE',
    token.`resource_target_id`,
    'KNOWLEDGE_IMPORT'
FROM (
    SELECT DISTINCT mapping.`api_key_id`, mapping.`resource_target_id`
    FROM `tb_sys_api_key_resource_mapping` mapping
    WHERE mapping.`resource_type` = 'KNOWLEDGE'
      AND mapping.`action_scope` = 'KNOWLEDGE_IMPORT'
) token
JOIN `tb_sys_api_key_resource` resource
  ON resource.`request_interface` IN (
      '/public-api/knowledge-share/document/import/batch',
      '/public-api/knowledge-share/document/import/batch/status',
      '/public-api/knowledge-share/document/import/batch/retry'
  )
LEFT JOIN `tb_sys_api_key_resource_mapping` existing
 ON existing.`api_key_id` = token.`api_key_id`
 AND existing.`api_key_resource_id` = resource.`id`
 AND existing.`resource_type` = 'KNOWLEDGE'
 AND existing.`resource_target_id` <=> token.`resource_target_id`
 AND existing.`action_scope` = 'KNOWLEDGE_IMPORT'
WHERE existing.`id` IS NULL;

SELECT
    @migrated_knowledge_api_key_count AS `migrated_knowledge_api_key_count`,
    @revoked_maintenance_mapping_count AS `revoked_maintenance_mapping_count`;

ALTER TABLE `tb_document_import_batch`
    ADD COLUMN `caller_type` varchar(16) NULL DEFAULT NULL
        COMMENT '调用者类型' AFTER `knowledge_id`,
    ADD COLUMN `caller_id` bigint UNSIGNED NULL DEFAULT NULL
        COMMENT '调用者ID' AFTER `caller_type`,
    ADD COLUMN `idempotency_key_hash` char(64) NULL DEFAULT NULL
        COMMENT '提交幂等键SHA-256' AFTER `caller_id`,
    ADD COLUMN `request_digest` char(64) NULL DEFAULT NULL
        COMMENT '请求摘要SHA-256' AFTER `idempotency_key_hash`,
    ADD COLUMN `duplicate_policy` varchar(16) NULL DEFAULT NULL
        COMMENT '重复文件策略' AFTER `request_digest`,
    ADD COLUMN `requested_strategy_json` text NULL
        COMMENT '请求分块策略' AFTER `duplicate_policy`,
    ADD COLUMN `retry_generation` int NOT NULL DEFAULT 0
        COMMENT '重试代次' AFTER `requested_strategy_json`,
    ADD COLUMN `last_retry_key_hash` char(64) NULL DEFAULT NULL
        COMMENT '最近重试幂等键SHA-256' AFTER `retry_generation`,
    ADD COLUMN `last_retry_generation` int NOT NULL DEFAULT 0
        COMMENT '最近重试响应代次' AFTER `last_retry_key_hash`,
    ADD COLUMN `version` int NOT NULL DEFAULT 0
        COMMENT '乐观锁版本' AFTER `last_retry_generation`,
    ADD UNIQUE INDEX `uk_document_import_batch_caller_idempotency`
        (`caller_type`, `caller_id`, `idempotency_key_hash`) USING BTREE;

UPDATE `tb_document_import_batch`
SET `caller_type` = 'ADMIN',
    `caller_id` = COALESCE(`created_by`, 0),
    `duplicate_policy` = COALESCE(`duplicate_policy`, 'SKIP')
WHERE `caller_type` IS NULL;

ALTER TABLE `tb_document_import_batch_item`
    ADD COLUMN `content_sha256` char(64) NULL DEFAULT NULL
        COMMENT '文件内容SHA-256' AFTER `file_path`,
    ADD COLUMN `failure_code` varchar(64) NULL DEFAULT NULL
        COMMENT '稳定失败码' AFTER `error_summary`,
    ADD COLUMN `applied_strategy_code` varchar(64) NULL DEFAULT NULL
        COMMENT '实际分块策略编码' AFTER `failure_code`,
    ADD COLUMN `strategy_snapshot_json` text NULL
        COMMENT '分块策略快照' AFTER `applied_strategy_code`,
    DROP INDEX `idx_document_import_batch_item_batch_status`,
    ADD INDEX `idx_document_import_batch_item_batch_status`
        (`batch_id`, `status`, `modified`, `id`) USING BTREE;

ALTER TABLE `tb_document_import_task`
    ADD COLUMN `failure_code` varchar(64) NULL DEFAULT NULL
        COMMENT '稳定失败码' AFTER `error_summary`,
    ADD COLUMN `attempt_no` int NOT NULL DEFAULT 0
        COMMENT '执行尝试次数' AFTER `failure_code`,
    ADD COLUMN `execution_token` varchar(64) NULL DEFAULT NULL
        COMMENT '执行令牌' AFTER `attempt_no`,
    ADD COLUMN `lease_until` datetime NULL DEFAULT NULL
        COMMENT '租约到期时间' AFTER `execution_token`,
    ADD COLUMN `version` int NOT NULL DEFAULT 0
        COMMENT '乐观锁版本' AFTER `lease_until`,
    ADD INDEX `idx_document_import_task_phase_status_lease`
        (`phase`, `status`, `lease_until`, `created`, `id`) USING BTREE;
