
-- Amenities table
CREATE TABLE public.amenities (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  association_id UUID REFERENCES public.associations(id) ON DELETE CASCADE NOT NULL,
  name TEXT NOT NULL,
  description TEXT,
  amenity_type TEXT NOT NULL DEFAULT 'info',
  cover_image_url TEXT,
  map_config JSONB DEFAULT '{}'::jsonb,
  booking_config JSONB DEFAULT '{}'::jsonb,
  form_fields JSONB DEFAULT '[]'::jsonb,
  is_active BOOLEAN NOT NULL DEFAULT true,
  sort_order INTEGER DEFAULT 0,
  created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
  updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

ALTER TABLE public.amenities ENABLE ROW LEVEL SECURITY;

CREATE POLICY "Staff can manage amenities" ON public.amenities
  FOR ALL TO authenticated
  USING (public.has_role(auth.uid(), 'admin') OR public.has_role(auth.uid(), 'manager') OR public.has_role(auth.uid(), 'employee'));

CREATE POLICY "Public can view active amenities" ON public.amenities
  FOR SELECT TO anon
  USING (is_active = true);

CREATE POLICY "Authenticated can view active amenities" ON public.amenities
  FOR SELECT TO authenticated
  USING (is_active = true);

-- Amenity booking requests
CREATE TABLE public.amenity_bookings (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  amenity_id UUID REFERENCES public.amenities(id) ON DELETE CASCADE NOT NULL,
  association_id UUID REFERENCES public.associations(id) ON DELETE CASCADE NOT NULL,
  guest_name TEXT NOT NULL,
  guest_email TEXT,
  guest_phone TEXT,
  booking_date DATE NOT NULL,
  start_time TEXT,
  end_time TEXT,
  notes TEXT,
  status TEXT NOT NULL DEFAULT 'pending',
  created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
  updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

ALTER TABLE public.amenity_bookings ENABLE ROW LEVEL SECURITY;

CREATE POLICY "Staff can manage bookings" ON public.amenity_bookings
  FOR ALL TO authenticated
  USING (public.has_role(auth.uid(), 'admin') OR public.has_role(auth.uid(), 'manager') OR public.has_role(auth.uid(), 'employee'));

CREATE POLICY "Anon can insert bookings" ON public.amenity_bookings
  FOR INSERT TO anon
  WITH CHECK (true);

-- Amenity form submissions
CREATE TABLE public.amenity_form_submissions (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  amenity_id UUID REFERENCES public.amenities(id) ON DELETE CASCADE NOT NULL,
  association_id UUID REFERENCES public.associations(id) ON DELETE CASCADE NOT NULL,
  submitter_name TEXT,
  submitter_email TEXT,
  form_data JSONB NOT NULL DEFAULT '{}'::jsonb,
  created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

ALTER TABLE public.amenity_form_submissions ENABLE ROW LEVEL SECURITY;

CREATE POLICY "Staff can view form submissions" ON public.amenity_form_submissions
  FOR ALL TO authenticated
  USING (public.has_role(auth.uid(), 'admin') OR public.has_role(auth.uid(), 'manager') OR public.has_role(auth.uid(), 'employee'));

CREATE POLICY "Anon can insert form submissions" ON public.amenity_form_submissions
  FOR INSERT TO anon
  WITH CHECK (true);
