-- Function to automatically add ride credit when user reviews a ride
CREATE OR REPLACE FUNCTION auto_add_ride_credit_on_review()
RETURNS TRIGGER
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = public
AS $$
BEGIN
  -- Only proceed if this is a ride review (not a park review)
  IF NEW.ride_id IS NOT NULL THEN
    -- Check if user already has this ride credit
    IF NOT EXISTS (
      SELECT 1 FROM public.user_ride_credits
      WHERE user_id = NEW.user_id AND ride_id = NEW.ride_id
    ) THEN
      -- Insert ride credit using visit_date from review if available
      INSERT INTO public.user_ride_credits (
        user_id,
        ride_id,
        first_ride_date,
        ride_count
      ) VALUES (
        NEW.user_id,
        NEW.ride_id,
        NEW.visit_date,
        1
      );
      
      RAISE NOTICE 'Auto-added ride credit for user % on ride %', NEW.user_id, NEW.ride_id;
    END IF;
  END IF;
  
  RETURN NEW;
END;
$$;

-- Trigger on review insert
CREATE TRIGGER auto_add_ride_credit_after_review
  AFTER INSERT ON public.reviews
  FOR EACH ROW
  EXECUTE FUNCTION auto_add_ride_credit_on_review();

-- Add helpful comment
COMMENT ON FUNCTION auto_add_ride_credit_on_review() IS 
  'Automatically adds a ride credit when a user reviews a ride they haven''t tracked yet. Uses visit_date from review as first_ride_date.';