CREATE TABLE IF NOT EXISTS user_delegation (
    id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    tenant_id BIGINT UNSIGNED NOT NULL,
    user_id BIGINT UNSIGNED NOT NULL,
    delegate_user_id BIGINT UNSIGNED NOT NULL,
    effective_from DATETIME NOT NULL,
    effective_to DATETIME NOT NULL,
    status VARCHAR(32) NOT NULL DEFAULT 'PENDING',
    reason VARCHAR(255) DEFAULT NULL,
    disabled_reason VARCHAR(255) DEFAULT NULL,
    is_deleted TINYINT(1) NOT NULL DEFAULT 0,
    created_by BIGINT UNSIGNED NOT NULL DEFAULT 0,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_by BIGINT UNSIGNED NOT NULL DEFAULT 0,
    updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    KEY idx_tenant_user_status (tenant_id, user_id, status),
    KEY idx_tenant_delegate_status (tenant_id, delegate_user_id, status),
    KEY idx_tenant_effective_to (tenant_id, effective_to)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

INSERT INTO permission (id, permission_code, permission_name, module)
VALUES
    (1052, 'user.delegation.manage', '代理授权管理', 'system')
ON DUPLICATE KEY UPDATE permission_name = VALUES(permission_name), module = VALUES(module);

INSERT INTO role_permission (id, tenant_id, role_id, permission_id)
VALUES
    (53, 1, 101, 1052)
ON DUPLICATE KEY UPDATE permission_id = VALUES(permission_id);
