-- 1. Add rental_id to signup_codes
ALTER TABLE public.signup_codes
ADD COLUMN IF NOT EXISTS rental_id uuid
  REFERENCES public.rv_boat_lot_rentals(id) ON DELETE SET NULL;

CREATE INDEX IF NOT EXISTS idx_signup_codes_rental_id
  ON public.signup_codes (rental_id);

-- 2. Update lookup_signup_code to return rental info as well
DROP FUNCTION IF EXISTS public.lookup_signup_code(text);

CREATE OR REPLACE FUNCTION public.lookup_signup_code(p_code text)
RETURNS TABLE(
  id uuid,
  role app_role,
  owner_id uuid,
  association_id uuid,
  rental_id uuid,
  expires_at timestamp with time zone,
  redeemed_at timestamp with time zone,
  owner_first_name text,
  owner_last_name text,
  owner_email text,
  association_name text,
  rental_renter_name text
)
LANGUAGE sql
STABLE SECURITY DEFINER
SET search_path TO 'public'
AS $function$
  SELECT
    sc.id, sc.role, sc.owner_id, sc.association_id, sc.rental_id,
    sc.expires_at, sc.redeemed_at,
    o.first_name, o.last_name, o.email,
    a.name,
    r.renter_name
  FROM public.signup_codes sc
  LEFT JOIN public.owners o ON o.id = sc.owner_id
  LEFT JOIN public.associations a ON a.id = sc.association_id
  LEFT JOIN public.rv_boat_lot_rentals r ON r.id = sc.rental_id
  WHERE sc.code = p_code
  LIMIT 1;
$function$;