-- Add missing columns to forum_topics table
-- Run this in Supabase SQL Editor

-- 1. Add upvotes_count column if it doesn't exist
ALTER TABLE public.forum_topics ADD COLUMN IF NOT EXISTS upvotes_count INTEGER DEFAULT 0;

-- 2. Add views_count column if it doesn't exist
ALTER TABLE public.forum_topics ADD COLUMN IF NOT EXISTS views_count INTEGER DEFAULT 0;

-- 3. Add replies_count column if it doesn't exist
ALTER TABLE public.forum_topics ADD COLUMN IF NOT EXISTS replies_count INTEGER DEFAULT 0;

-- 4. Add last_reply_at column if it doesn't exist
ALTER TABLE public.forum_topics ADD COLUMN IF NOT EXISTS last_reply_at TIMESTAMP WITH TIME ZONE;

-- 5. Update existing records to have correct default values
UPDATE public.forum_topics 
SET 
  upvotes_count = COALESCE(upvotes, 0),
  views_count = COALESCE(views_count, 0),
  replies_count = COALESCE(replies_count, 0)
WHERE upvotes_count IS NULL OR views_count IS NULL OR replies_count IS NULL;

-- 6. Make sure the upvotes column exists and has a default value
ALTER TABLE public.forum_topics ALTER COLUMN upvotes SET DEFAULT 0;
ALTER TABLE public.forum_topics ALTER COLUMN upvotes_count SET DEFAULT 0;
ALTER TABLE public.forum_topics ALTER COLUMN views_count SET DEFAULT 0;
ALTER TABLE public.forum_topics ALTER COLUMN replies_count SET DEFAULT 0;
