-- Migration: Add is_latest and revision tracking columns

-- 1. 添加新欄位到 journal_entries
ALTER TABLE journal_entries 
ADD COLUMN IF NOT EXISTS is_latest BOOLEAN DEFAULT true,
ADD COLUMN IF NOT EXISTS revision_count INTEGER DEFAULT 1,
ADD COLUMN IF NOT EXISTS original_entry_id INTEGER REFERENCES journal_entries(journal_entry_id) ON DELETE CASCADE;

-- 2. 處理現有數據
-- 將所有已刪除的交易標記為 is_latest = false
UPDATE journal_entries 
SET is_latest = false 
WHERE is_deleted = true AND is_latest IS NOT NULL;

-- 將所有活躍交易標記為 is_latest = true
UPDATE journal_entries 
SET is_latest = true 
WHERE is_deleted = false AND is_latest IS NULL;

-- 3. 創建索引以提高查詢性能
CREATE INDEX IF NOT EXISTS idx_journal_entries_is_latest 
ON journal_entries(is_latest, entry_date);

CREATE INDEX IF NOT EXISTS idx_journal_entries_original_entry_id 
ON journal_entries(original_entry_id);

-- 4. 添加註釋說明
COMMENT ON COLUMN journal_entries.is_latest IS '是否為最新版本（試算表使用此欄位過濾）';
COMMENT ON COLUMN journal_entries.revision_count IS '修正版次（原始=1, 第1次修正=2, ...）';
COMMENT ON COLUMN journal_entries.original_entry_id IS '指向原始交易（如果是修正版本）';
