-- Миграция путей Nextcloud с /crm2/ на /crm/
-- Дата: 2025-10-20

-- 1. Создание резервной копии
CREATE TABLE IF NOT EXISTS vtiger_notes_backup_20251020 LIKE vtiger_notes;
INSERT INTO vtiger_notes_backup_20251020 SELECT * FROM vtiger_notes;

-- 2. Обновление s3_key: crm2/ → crm/
UPDATE vtiger_notes 
SET s3_key = REPLACE(s3_key, 'crm2/', 'crm/') 
WHERE s3_key LIKE 'crm2/%';

-- 3. Обновление nc_path с дублированием: /crm2/crm2/ → /crm/
UPDATE vtiger_notes 
SET nc_path = REPLACE(nc_path, '/crm2/crm2/', '/crm/') 
WHERE nc_path LIKE '/crm2/crm2/%';

-- 4. Обновление nc_path: /crm2/ → /crm/
UPDATE vtiger_notes 
SET nc_path = REPLACE(nc_path, '/crm2/', '/crm/') 
WHERE nc_path LIKE '/crm2/%';

-- 5. Обновление filename (S3 URLs): /crm2/ → /crm/
UPDATE vtiger_notes 
SET filename = REPLACE(filename, '/crm2/', '/crm/') 
WHERE filename LIKE '%/crm2/%' AND filelocationtype = 'E';

-- Проверка результатов
SELECT 'Проверка: s3_key с crm2/' as check_name, COUNT(*) as count FROM vtiger_notes WHERE s3_key LIKE 'crm2/%'
UNION ALL
SELECT 'Проверка: nc_path с /crm2/', COUNT(*) FROM vtiger_notes WHERE nc_path LIKE '/crm2/%'
UNION ALL
SELECT 'Проверка: filename с /crm2/', COUNT(*) FROM vtiger_notes WHERE filename LIKE '%/crm2/%' AND filelocationtype = 'E'
UNION ALL
SELECT 'Итого: s3_key с crm/', COUNT(*) FROM vtiger_notes WHERE s3_key LIKE 'crm/%'
UNION ALL
SELECT 'Итого: nc_path с /crm/', COUNT(*) FROM vtiger_notes WHERE nc_path LIKE '/crm/%';

-- Проверка конкретного документа 395695
SELECT 
    notesid,
    s3_key,
    nc_path,
    SUBSTRING(filename, 1, 100) as filename_preview
FROM vtiger_notes 
WHERE notesid = 395695;

