-- Add image_url column to events table
ALTER TABLE events ADD COLUMN image_url TEXT;

-- Create storage bucket for event images
INSERT INTO storage.buckets (id, name, public)
VALUES ('event-images', 'event-images', true);

-- Create storage policy for authenticated users to upload event images
CREATE POLICY "Users can upload event images" ON storage.objects
FOR INSERT WITH CHECK (
  bucket_id = 'event-images' AND
  auth.uid() IS NOT NULL
);

-- Create storage policy for public read access to event images
CREATE POLICY "Public read access to event images" ON storage.objects
FOR SELECT USING (bucket_id = 'event-images');

-- Create storage policy for users to delete their own event images
CREATE POLICY "Users can delete their own event images" ON storage.objects
FOR DELETE USING (
  bucket_id = 'event-images' AND
  auth.uid() IS NOT NULL
);

-- Update RLS policy for events to include image_url in SELECT
DROP POLICY IF EXISTS "Users can view events in their organization" ON events;
CREATE POLICY "Users can view events in their organization" ON events
FOR SELECT USING (
  organization_id IN (
    SELECT organization_id FROM users WHERE user_id = auth.uid()
  )
);

-- Update RLS policy for events to include image_url in INSERT
DROP POLICY IF EXISTS "Users can create events in their organization" ON events;
CREATE POLICY "Users can create events in their organization" ON events
FOR INSERT WITH CHECK (
  organization_id IN (
    SELECT organization_id FROM users WHERE user_id = auth.uid()
  )
);

-- Update RLS policy for events to include image_url in UPDATE
DROP POLICY IF EXISTS "Users can update events in their organization" ON events;
CREATE POLICY "Users can update events in their organization" ON events
FOR UPDATE USING (
  organization_id IN (
    SELECT organization_id FROM users WHERE user_id = auth.uid()
  )
);

-- Add index on image_url for faster queries
CREATE INDEX IF NOT EXISTS idx_events_image_url ON events(image_url) WHERE image_url IS NOT NULL;