SET NAMES utf8mb4;

DROP PROCEDURE IF EXISTS `sp_add_column_if_missing`;
DROP PROCEDURE IF EXISTS `sp_drop_index_if_exists`;
DROP PROCEDURE IF EXISTS `sp_add_index_if_missing`;

DELIMITER $$
CREATE PROCEDURE `sp_add_column_if_missing`(
    IN in_table_name VARCHAR(128),
    IN in_column_name VARCHAR(128),
    IN in_definition TEXT
)
BEGIN
    IF NOT EXISTS (
        SELECT 1
        FROM information_schema.COLUMNS
        WHERE TABLE_SCHEMA = DATABASE()
          AND TABLE_NAME = in_table_name
          AND COLUMN_NAME = in_column_name
    ) THEN
        SET @ddl = CONCAT('ALTER TABLE `', in_table_name, '` ADD COLUMN ', in_definition);
        PREPARE stmt FROM @ddl;
        EXECUTE stmt;
        DEALLOCATE PREPARE stmt;
    END IF;
END $$

CREATE PROCEDURE `sp_drop_index_if_exists`(
    IN in_table_name VARCHAR(128),
    IN in_index_name VARCHAR(128)
)
BEGIN
    IF EXISTS (
        SELECT 1
        FROM information_schema.STATISTICS
        WHERE TABLE_SCHEMA = DATABASE()
          AND TABLE_NAME = in_table_name
          AND INDEX_NAME = in_index_name
    ) THEN
        SET @ddl = CONCAT('ALTER TABLE `', in_table_name, '` DROP INDEX `', in_index_name, '`');
        PREPARE stmt FROM @ddl;
        EXECUTE stmt;
        DEALLOCATE PREPARE stmt;
    END IF;
END $$

CREATE PROCEDURE `sp_add_index_if_missing`(
    IN in_table_name VARCHAR(128),
    IN in_index_name VARCHAR(128),
    IN in_definition TEXT
)
BEGIN
    IF NOT EXISTS (
        SELECT 1
        FROM information_schema.STATISTICS
        WHERE TABLE_SCHEMA = DATABASE()
          AND TABLE_NAME = in_table_name
          AND INDEX_NAME = in_index_name
    ) THEN
        SET @ddl = CONCAT('ALTER TABLE `', in_table_name, '` ADD ', in_definition);
        PREPARE stmt FROM @ddl;
        EXECUTE stmt;
        DEALLOCATE PREPARE stmt;
    END IF;
END $$
DELIMITER ;

CALL `sp_add_column_if_missing`('tb_sys_api_key_resource_mapping', 'resource_type',
                                '`resource_type` varchar(32) NULL DEFAULT NULL COMMENT ''资源类型'' AFTER `api_key_resource_id`');
CALL `sp_add_column_if_missing`('tb_sys_api_key_resource_mapping', 'resource_target_id',
                                '`resource_target_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT ''资源目标ID'' AFTER `resource_type`');
CALL `sp_add_column_if_missing`('tb_sys_api_key_resource_mapping', 'action_scope',
                                '`action_scope` varchar(64) NULL DEFAULT NULL COMMENT ''动作范围'' AFTER `resource_target_id`');

CALL `sp_drop_index_if_exists`('tb_sys_api_key_resource_mapping', 'uni_api_key_resource');
CALL `sp_add_index_if_missing`(
    'tb_sys_api_key_resource_mapping',
    'uni_api_key_resource_scope',
    'UNIQUE INDEX `uni_api_key_resource_scope`(`api_key_id`, `api_key_resource_id`, `resource_type`, `resource_target_id`, `action_scope`) USING BTREE'
);
CALL `sp_add_index_if_missing`(
    'tb_sys_api_key_resource_mapping',
    'idx_api_key_resource_scope_lookup',
    'INDEX `idx_api_key_resource_scope_lookup`(`api_key_id`, `resource_type`, `resource_target_id`, `action_scope`) USING BTREE'
);

CREATE TABLE IF NOT EXISTS `tb_knowledge_share`
(
    `id`               bigint UNSIGNED NOT NULL COMMENT 'ID',
    `knowledge_id`     bigint UNSIGNED NOT NULL COMMENT '知识库ID',
    `share_type`       varchar(32) NOT NULL COMMENT '分享类型',
    `share_code`       varchar(64) NOT NULL COMMENT '分享码',
    `share_token_hash` varchar(128) NOT NULL COMMENT '分享令牌哈希',
    `status`           varchar(32) NOT NULL COMMENT '分享状态',
    `permission_set`   text NULL COMMENT '授权范围',
    `expires_at`       datetime NOT NULL COMMENT '过期时间',
    `tenant_id`        bigint UNSIGNED NOT NULL COMMENT '租户ID',
    `dept_id`          bigint UNSIGNED NOT NULL COMMENT '部门ID',
    `created`          datetime NULL DEFAULT NULL COMMENT '创建时间',
    `created_by`       bigint UNSIGNED NULL DEFAULT NULL COMMENT '创建人',
    `modified`         datetime NULL DEFAULT NULL COMMENT '修改时间',
    `modified_by`      bigint UNSIGNED NULL DEFAULT NULL COMMENT '修改人',
    PRIMARY KEY (`id`) USING BTREE,
    UNIQUE INDEX `uni_knowledge_share_code`(`share_code`) USING BTREE,
    INDEX `idx_knowledge_share_knowledge_id`(`knowledge_id`) USING BTREE,
    INDEX `idx_knowledge_share_expires_at`(`expires_at`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '知识库分享记录' ROW_FORMAT = Dynamic;

DROP PROCEDURE IF EXISTS `sp_add_column_if_missing`;
DROP PROCEDURE IF EXISTS `sp_drop_index_if_exists`;
DROP PROCEDURE IF EXISTS `sp_add_index_if_missing`;
