-- Rename heritage_timeline_items to timeline_items and add heritage column
-- This migration supports the refactoring of HeritageTimelineItem to TimelineItem

-- Check if we need to rename the table
DO $$
BEGIN
    -- Only rename if heritage_timeline_items exists and timeline_items doesn't
    IF EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'heritage_timeline_items' AND table_schema = 'public')
       AND NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'timeline_items' AND table_schema = 'public') THEN
        -- Rename table
        ALTER TABLE heritage_timeline_items RENAME TO timeline_items;
    END IF;
END $$;

-- Add heritage column if it doesn't exist
DO $$
BEGIN
    IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = 'timeline_items' AND column_name = 'heritage' AND table_schema = 'public') THEN
        ALTER TABLE timeline_items ADD COLUMN heritage BOOLEAN NOT NULL DEFAULT true;
    END IF;
END $$;

-- Rename index if needed
DO $$
BEGIN
    IF EXISTS (SELECT 1 FROM pg_indexes WHERE tablename = 'timeline_items' AND indexname = 'idx_timeline_order') THEN
        DROP INDEX IF EXISTS idx_timeline_order;
    END IF;
    IF NOT EXISTS (SELECT 1 FROM pg_indexes WHERE tablename = 'timeline_items' AND indexname = 'idx_timeline_items_order') THEN
        CREATE INDEX IF NOT EXISTS idx_timeline_items_order ON timeline_items("order");
    END IF;
END $$;

-- Update trigger name if needed
DO $$
BEGIN
    IF EXISTS (SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'update_heritage_timeline_items_updated_at' AND event_object_table = 'timeline_items') THEN
        DROP TRIGGER IF EXISTS update_heritage_timeline_items_updated_at ON timeline_items;
    END IF;
    IF NOT EXISTS (SELECT 1 FROM information_schema.triggers WHERE trigger_name = 'update_timeline_items_updated_at' AND event_object_table = 'timeline_items') THEN
        CREATE TRIGGER update_timeline_items_updated_at BEFORE UPDATE ON timeline_items
            FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();
    END IF;
END $$;
