-- Create function to increment referral code uses
CREATE OR REPLACE FUNCTION increment_referral_uses(ref_code text)
RETURNS void
LANGUAGE plpgsql
SECURITY DEFINER
AS $$
BEGIN
  UPDATE public.referral_codes
  SET uses_count = uses_count + 1,
      updated_at = now()
  WHERE code = ref_code AND is_active = true;
END;
$$;

-- Grant execute permission
GRANT EXECUTE ON FUNCTION increment_referral_uses(text) TO anon, authenticated;
