-- 既存の全仕訳のparent_entry_idを一括設定

-- ステップ1: 現在の状況を確認
SELECT 
    journal_entry_id,
    entry_date,
    description,
    parent_entry_id,
    is_deleted
FROM journal_entries
ORDER BY entry_date, journal_entry_id;

-- ステップ2: [逆仕訳]のparent_entry_idを設定
-- [逆仕訳]の直前の同じ日付・同じベース説明の仕訳を親とする
UPDATE journal_entries je_reverse
SET parent_entry_id = (
    SELECT je_original.journal_entry_id
    FROM journal_entries je_original
    WHERE je_original.entry_date = je_reverse.entry_date
    AND je_original.journal_entry_id < je_reverse.journal_entry_id
    AND REPLACE(je_reverse.description, '[逆仕訳] ', '') = je_original.description
    AND je_original.description NOT LIKE '[逆仕訳]%'
    ORDER BY je_original.journal_entry_id DESC
    LIMIT 1
)
WHERE je_reverse.description LIKE '[逆仕訳]%'
AND je_reverse.parent_entry_id IS NULL;

-- ステップ3: 【修正後】のparent_entry_idを設定
-- 【修正後】の直前の逆仕訳を親とする
UPDATE journal_entries je_modified
SET parent_entry_id = (
    SELECT je_reverse.journal_entry_id
    FROM journal_entries je_reverse
    WHERE je_reverse.journal_entry_id < je_modified.journal_entry_id
    AND je_reverse.description = '[逆仕訳] ' || REPLACE(je_modified.description, '【修正後】', '')
    ORDER BY je_reverse.journal_entry_id DESC
    LIMIT 1
)
WHERE je_modified.description LIKE '【修正後】%'
AND je_modified.parent_entry_id IS NULL;

-- ステップ4: 複数の【修正後】プレフィックスがある場合の処理
-- 【修正後】【修正後】などのケース
UPDATE journal_entries je_modified
SET parent_entry_id = (
    SELECT je_reverse.journal_entry_id
    FROM journal_entries je_reverse
    WHERE je_reverse.entry_date = je_modified.entry_date
    AND je_reverse.journal_entry_id < je_modified.journal_entry_id
    AND je_reverse.description LIKE '[逆仕訳]%'
    ORDER BY je_reverse.journal_entry_id DESC
    LIMIT 1
)
WHERE je_modified.description LIKE '【修正後】%'
AND je_modified.parent_entry_id IS NULL;

-- ステップ5: 結果確認
SELECT 
    journal_entry_id,
    entry_date,
    LEFT(description, 50) as description,
    parent_entry_id,
    is_deleted
FROM journal_entries
WHERE parent_entry_id IS NOT NULL
ORDER BY entry_date, journal_entry_id;

-- ステップ6: parent_entry_idが設定されていない逆仕訳・修正後を確認
SELECT 
    journal_entry_id,
    entry_date,
    LEFT(description, 50) as description,
    parent_entry_id
FROM journal_entries
WHERE (description LIKE '[逆仕訳]%' OR description LIKE '【修正後】%')
AND parent_entry_id IS NULL
ORDER BY journal_entry_id;
