CREATE OR REPLACE PROCEDURE SP_ADD_CONSUMER_REQUEST_TOKEN
(
P_TOKEN_TTL                    IN        NUMBER, -- IN SECOND
P_CONSUMER_KEY                 IN        VARCHAR2,
P_TOKEN                        IN        VARCHAR2,
P_TOKEN_SECRET                 IN        VARCHAR2,
P_CALLBACK_URL                 IN        VARCHAR2,
P_RESULT                       OUT       NUMBER
)
AS

 -- PROCEDURE TO Add an unautorized request token to our server.
 
V_OSR_ID                                    NUMBER;
V_OSR_ID_REF                                NUMBER;

V_EXC_NO_SERVER_EXIST                       EXCEPTION;
BEGIN

  P_RESULT := 0;
 
 BEGIN 
 SELECT OSR_ID INTO V_OSR_ID
  FROM OAUTH_SERVER_REGISTRY
  WHERE OSR_CONSUMER_KEY = P_CONSUMER_KEY
  AND OSR_ENABLED      = 1;
 EXCEPTION
 WHEN NO_DATA_FOUND THEN
      RAISE V_EXC_NO_SERVER_EXIST;
 END;
 

BEGIN 
  SELECT OST_OSR_ID_REF INTO V_OSR_ID_REF
  FROM OAUTH_SERVER_TOKEN
  WHERE OST_OSR_ID_REF = V_OSR_ID;
  
  UPDATE OAUTH_SERVER_TOKEN
  	SET OST_OSR_ID_REF		= V_OSR_ID,
					OST_USA_ID_REF		= 1,
					OST_TOKEN			= P_TOKEN,
					OST_TOKEN_SECRET	= P_TOKEN_SECRET,
					OST_TOKEN_TYPE		= 'REQUEST',
					OST_TOKEN_TTL       = SYSDATE + (P_TOKEN_TTL/(24*60*60)),
					OST_CALLBACK_URL    = P_CALLBACK_URL,
          OST_TIMESTAMP		= SYSDATE
     WHERE OST_OSR_ID_REF = V_OSR_ID_REF;
  

 EXCEPTION
 WHEN NO_DATA_FOUND THEN
      
    INSERT INTO OAUTH_SERVER_TOKEN
    (OST_ID, OST_OSR_ID_REF, OST_USA_ID_REF, OST_TOKEN, OST_TOKEN_SECRET, OST_TOKEN_TYPE, 
    OST_TOKEN_TTL, OST_CALLBACK_URL)
    VALUES
    (SEQ_OCT_ID.NEXTVAL, V_OSR_ID, 1, P_TOKEN, P_TOKEN_SECRET, 'REQUEST', SYSDATE + (P_TOKEN_TTL/(24*60*60)),
    P_CALLBACK_URL);
    
 END;
 

EXCEPTION
WHEN V_EXC_NO_SERVER_EXIST THEN
P_RESULT := 2; -- NO_SERVER_EXIST
WHEN OTHERS THEN
-- CALL THE FUNCTION TO LOG ERRORS
ROLLBACK;
P_RESULT := 1; -- ERROR
END;
/
