-- Add new columns to status_updates
ALTER TABLE public.status_updates
  ADD COLUMN IF NOT EXISTS image_urls jsonb DEFAULT '[]'::jsonb,
  ADD COLUMN IF NOT EXISTS requested_action text,
  ADD COLUMN IF NOT EXISTS voting_enabled boolean DEFAULT false;

-- Create status_update_comments table
CREATE TABLE IF NOT EXISTS public.status_update_comments (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  status_update_id uuid NOT NULL REFERENCES public.status_updates(id) ON DELETE CASCADE,
  user_id uuid NOT NULL,
  content text NOT NULL,
  created_at timestamptz NOT NULL DEFAULT now()
);

ALTER TABLE public.status_update_comments ENABLE ROW LEVEL SECURITY;

CREATE POLICY "Authenticated users can view status_update_comments"
  ON public.status_update_comments FOR SELECT TO authenticated
  USING (true);

CREATE POLICY "Authenticated users can insert status_update_comments"
  ON public.status_update_comments FOR INSERT TO authenticated
  WITH CHECK (auth.uid() = user_id);

CREATE POLICY "Users can delete own comments"
  ON public.status_update_comments FOR DELETE TO authenticated
  USING (user_id = auth.uid());

-- Create status_update_votes table
CREATE TABLE IF NOT EXISTS public.status_update_votes (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  status_update_id uuid NOT NULL REFERENCES public.status_updates(id) ON DELETE CASCADE,
  user_id uuid NOT NULL,
  vote text NOT NULL,
  created_at timestamptz NOT NULL DEFAULT now(),
  UNIQUE (status_update_id, user_id)
);

ALTER TABLE public.status_update_votes ENABLE ROW LEVEL SECURITY;

CREATE POLICY "Authenticated users can view status_update_votes"
  ON public.status_update_votes FOR SELECT TO authenticated
  USING (true);

CREATE POLICY "Authenticated users can insert status_update_votes"
  ON public.status_update_votes FOR INSERT TO authenticated
  WITH CHECK (auth.uid() = user_id);

CREATE POLICY "Users can update own votes"
  ON public.status_update_votes FOR UPDATE TO authenticated
  USING (user_id = auth.uid())
  WITH CHECK (user_id = auth.uid());

-- Create storage bucket for status update images
INSERT INTO storage.buckets (id, name, public)
VALUES ('status-update-images', 'status-update-images', true)
ON CONFLICT (id) DO NOTHING;

-- Storage policies
CREATE POLICY "Authenticated users can upload status update images"
  ON storage.objects FOR INSERT TO authenticated
  WITH CHECK (bucket_id = 'status-update-images');

CREATE POLICY "Anyone can view status update images"
  ON storage.objects FOR SELECT TO public
  USING (bucket_id = 'status-update-images');

CREATE POLICY "Authenticated users can delete status update images"
  ON storage.objects FOR DELETE TO authenticated
  USING (bucket_id = 'status-update-images');