ALTER TABLE public.amenity_bookings
ADD COLUMN IF NOT EXISTS booking_type TEXT NOT NULL DEFAULT 'rental',
ADD COLUMN IF NOT EXISTS title TEXT,
ADD COLUMN IF NOT EXISTS end_time TIME WITHOUT TIME ZONE,
ADD COLUMN IF NOT EXISTS location TEXT,
ADD COLUMN IF NOT EXISTS form_data JSONB NOT NULL DEFAULT '{}'::jsonb,
ADD COLUMN IF NOT EXISTS created_by UUID;

ALTER TABLE public.amenity_bookings
DROP CONSTRAINT IF EXISTS amenity_bookings_booking_type_check;

ALTER TABLE public.amenity_bookings
ADD CONSTRAINT amenity_bookings_booking_type_check
CHECK (booking_type IN ('rental', 'meeting'));

CREATE INDEX IF NOT EXISTS idx_amenity_bookings_assoc_type_date
ON public.amenity_bookings (association_id, booking_type, booking_date);

CREATE INDEX IF NOT EXISTS idx_amenity_bookings_amenity_date
ON public.amenity_bookings (amenity_id, booking_date);

ALTER TABLE public.amenity_bookings ENABLE ROW LEVEL SECURITY;

DROP POLICY IF EXISTS "Staff can manage amenity bookings" ON public.amenity_bookings;
DROP POLICY IF EXISTS "Association users can view amenity bookings" ON public.amenity_bookings;
DROP POLICY IF EXISTS "Public can create amenity booking requests" ON public.amenity_bookings;

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

CREATE POLICY "Association users can view amenity bookings"
ON public.amenity_bookings
FOR SELECT
TO authenticated
USING (
  association_id IN (SELECT public.get_user_association_ids())
  OR public.has_role(auth.uid(), 'admin'::public.app_role)
  OR public.has_role(auth.uid(), 'manager'::public.app_role)
);

CREATE POLICY "Public can create amenity booking requests"
ON public.amenity_bookings
FOR INSERT
TO anon, authenticated
WITH CHECK (
  EXISTS (
    SELECT 1
    FROM public.amenities a
    WHERE a.id = amenity_bookings.amenity_id
      AND a.association_id = amenity_bookings.association_id
      AND a.is_active = true
      AND a.amenity_type IN ('booking', 'rental_calendar', 'meeting_calendar')
  )
);

DROP TRIGGER IF EXISTS update_amenity_bookings_updated_at ON public.amenity_bookings;
CREATE TRIGGER update_amenity_bookings_updated_at
BEFORE UPDATE ON public.amenity_bookings
FOR EACH ROW
EXECUTE FUNCTION public.update_updated_at_column();