-- Reverse: Rename timeline_items back to heritage_timeline_items and remove heritage column

-- Remove heritage column if it exists
DO $$
BEGIN
    IF 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 DROP COLUMN heritage;
    END IF;
END $$;

-- Rename table back if needed
DO $$
BEGIN
    IF EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'timeline_items' AND table_schema = 'public')
       AND NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'heritage_timeline_items' AND table_schema = 'public') THEN
        ALTER TABLE timeline_items RENAME TO heritage_timeline_items;
    END IF;
END $$;

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

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