-- 修正後の仕訳に対して、元の仕訳IDをparent_entry_idに設定

-- 特定の修正チェーンを手動で設定（72 → 79 → 80）
-- UPDATE journal_entries SET parent_entry_id = 72 WHERE journal_entry_id = 79;
-- UPDATE journal_entries SET parent_entry_id = 79 WHERE journal_entry_id = 80;

-- ステップ1: 【修正後】の仕訳を確認
SELECT 
    je_modified.journal_entry_id as modified_id,
    je_modified.description as modified_desc,
    je_original.journal_entry_id as original_id,
    je_original.description as original_desc
FROM journal_entries je_modified
LEFT JOIN journal_entries je_original 
    ON REPLACE(je_modified.description, '【修正後】', '') = je_original.description
    AND je_modified.description LIKE '【修正後】%'
    AND je_original.description NOT LIKE '【修正後】%'
    AND je_original.description NOT LIKE '[逆仕訳]%'
WHERE je_modified.description LIKE '【修正後】%'
ORDER BY je_modified.journal_entry_id;

-- ステップ2: 確認後、以下のUPDATE文を実行
UPDATE journal_entries 
SET parent_entry_id = je_original.journal_entry_id
FROM journal_entries je_original
WHERE REPLACE(journal_entries.description, '【修正後】', '') = je_original.description
  AND journal_entries.description LIKE '【修正後】%'
  AND je_original.description NOT LIKE '【修正後】%'
  AND je_original.description NOT LIKE '[逆仕訳]%';
