-- Link rentals to a portal user
ALTER TABLE public.rv_boat_lot_rentals
  ADD COLUMN IF NOT EXISTS user_id UUID REFERENCES auth.users(id) ON DELETE SET NULL;

CREATE INDEX IF NOT EXISTS rv_boat_lot_rentals_user_idx ON public.rv_boat_lot_rentals(user_id);

-- Helper: get owner_ids the current rv_renter has access to (via their rental)
CREATE OR REPLACE FUNCTION public.get_rv_renter_owner_ids(_user_id uuid DEFAULT auth.uid())
RETURNS SETOF uuid
LANGUAGE sql STABLE SECURITY DEFINER SET search_path = public
AS $$
  SELECT DISTINCT r.owner_id
  FROM public.rv_boat_lot_rentals r
  WHERE r.user_id = _user_id
    AND r.owner_id IS NOT NULL
    AND r.status = 'active'
$$;

CREATE OR REPLACE FUNCTION public.get_rv_renter_association_ids(_user_id uuid DEFAULT auth.uid())
RETURNS SETOF uuid
LANGUAGE sql STABLE SECURITY DEFINER SET search_path = public
AS $$
  SELECT DISTINCT r.association_id
  FROM public.rv_boat_lot_rentals r
  WHERE r.user_id = _user_id
    AND r.status = 'active'
$$;

-- Allow rv_renter to read their own rental
CREATE POLICY "RV renters can view their own rental"
ON public.rv_boat_lot_rentals
FOR SELECT
TO authenticated
USING (user_id = auth.uid());

-- Allow rv_renter to read their lot
CREATE POLICY "RV renters can view their lot"
ON public.rv_boat_lots
FOR SELECT
TO authenticated
USING (
  EXISTS (
    SELECT 1 FROM public.rv_boat_lot_rentals r
    WHERE r.lot_id = rv_boat_lots.id
      AND r.user_id = auth.uid()
      AND r.status = 'active'
  )
);

-- Allow rv_renter to read their association (name, etc.)
CREATE POLICY "RV renters can view their association"
ON public.associations
FOR SELECT
TO authenticated
USING (id IN (SELECT public.get_rv_renter_association_ids(auth.uid())));

-- Allow rv_renter to read the linked owner ledger
CREATE POLICY "RV renters can view linked owner ledger"
ON public.owner_ledger_entries
FOR SELECT
TO authenticated
USING (owner_id IN (SELECT public.get_rv_renter_owner_ids(auth.uid())));

-- Allow rv_renter to read the linked owner record (for name/balance display)
CREATE POLICY "RV renters can view linked owner"
ON public.owners
FOR SELECT
TO authenticated
USING (id IN (SELECT public.get_rv_renter_owner_ids(auth.uid())));
