-- Create photos table for storing entity photos with CloudFlare integration
CREATE TABLE IF NOT EXISTS public.photos (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  cloudflare_image_id TEXT NOT NULL,
  cloudflare_image_url TEXT NOT NULL,
  entity_type TEXT NOT NULL CHECK (entity_type IN ('park', 'ride', 'manufacturer', 'operator', 'designer', 'property_owner')),
  entity_id UUID NOT NULL,
  title TEXT,
  caption TEXT,
  photographer_credit TEXT,
  date_taken DATE,
  order_index INTEGER DEFAULT 0,
  is_featured BOOLEAN DEFAULT false,
  submission_id UUID,
  submitted_by UUID,
  approved_by UUID,
  approved_at TIMESTAMP WITH TIME ZONE,
  created_at TIMESTAMP WITH TIME ZONE DEFAULT now() NOT NULL,
  updated_at TIMESTAMP WITH TIME ZONE DEFAULT now() NOT NULL
);

-- Create indexes for efficient queries
CREATE INDEX idx_photos_entity ON public.photos(entity_type, entity_id);
CREATE INDEX idx_photos_submission ON public.photos(submission_id);
CREATE INDEX idx_photos_featured ON public.photos(entity_type, entity_id, is_featured) WHERE is_featured = true;
CREATE INDEX idx_photos_order ON public.photos(entity_type, entity_id, order_index);

-- Enable Row Level Security
ALTER TABLE public.photos ENABLE ROW LEVEL SECURITY;

-- Public can view approved photos
CREATE POLICY "Public read access to photos"
  ON public.photos
  FOR SELECT
  USING (true);

-- Authenticated users can submit photos (for future direct upload)
CREATE POLICY "Users can create photos"
  ON public.photos
  FOR INSERT
  WITH CHECK (auth.uid() = submitted_by);

-- Moderators can manage all photos
CREATE POLICY "Moderators can update photos"
  ON public.photos
  FOR UPDATE
  USING (is_moderator(auth.uid()));

CREATE POLICY "Moderators can delete photos"
  ON public.photos
  FOR DELETE
  USING (is_moderator(auth.uid()));

-- Create trigger to update updated_at timestamp
CREATE TRIGGER update_photos_updated_at
  BEFORE UPDATE ON public.photos
  FOR EACH ROW
  EXECUTE FUNCTION public.update_updated_at_column();