text: -- PREREQ: REMOVE_EXPIRED_SUBSCRIBERS
  -- RETURNS -
  -- 0 -> ALL OKAY
  -- 1 -> NOT A SUB
  -- 2 -> LIMIT CROSSED
  -- 3 -> BOOK NOT AVAILABLE
  -- 4 -> ALREADY BORROWED
  
  CREATE OR REPLACE FUNCTION ACCEPT_BORROW_REQUEST (ARG_CUSTOMER_ID IN VARCHAR2, ARG_ISBN IN VARCHAR2, ARG_CURRENT_DATE IN DATE)
  RETURN NUMBER IS
  
  	CNT_SUB NUMBER;
  	CNT_BOOKS_IN_ITEMS NUMBER;
  	CNT_ALREADY_BORROWED NUMBER;
  	CNT_LIMIT NUMBER;
  	B_ID NUMBER;
  	CNT_BOOKS_IN_BORROWS NUMBER;
  	BEGIN
  		REMOVE_EXPIRED_SUBSCRIBERS(ARG_CURRENT_DATE);
  		SELECT COUNT(*) INTO CNT_SUB FROM SUBSCRIBERS WHERE CUSTOMER_ID = ARG_CUSTOMER_ID;
  
  		IF CNT_SUB = 0 THEN
              RETURN 1;
          END IF;
  		SELECT COUNT(*) INTO CNT_BOOKS_IN_BORROWS
  		FROM BORROWS A
  		INNER JOIN BORROWABLE_ITEMS B USING(BORROWABLE_ITEM_ID)
  		WHERE A.CUSTOMER_ID = ARG_CUSTOMER_ID AND B.ISBN = ARG_ISBN;
  
  		IF CNT_BOOKS_IN_BORROWS <> 0 THEN
  			RETURN 4;
  		END IF;
  
  		SELECT COUNT(*) INTO CNT_ALREADY_BORROWED FROM BORROWS WHERE CUSTOMER_ID = ARG_CUSTOMER_ID;
  		SELECT P.BORROW_LIMIT INTO CNT_LIMIT
  		    FROM PLANS P
  		    WHERE P.PLAN_ID = (
  		        SELECT S.PLAN_ID
  		        FROM SUBSCRIBERS S
  		        WHERE S.CUSTOMER_ID = ARG_CUSTOMER_ID
  		    );
  		IF CNT_LIMIT <= CNT_ALREADY_BORROWED THEN
              RETURN 2;
          END IF;
  		SELECT BORROWABLE_ITEM_ID INTO B_ID
  		FROM
  		(((SELECT BORROWABLE_ITEM_ID FROM BORROWABLE_ITEMS WHERE ISBN = ARG_ISBN)
  	    MINUS
  	    (SELECT BORROWABLE_ITEM_ID FROM BORROWS WHERE END_DATE IS NULL))
  	    MINUS
  	    (SELECT BORROWABLE_ITEM_ID FROM EXPIRED))
  		WHERE ROWNUM = 1;
  
          INSERT INTO
              BORROWS(BORROWABLE_ITEM_ID, CUSTOMER_ID, START_DATE)
              VALUES (B_ID, ARG_CUSTOMER_ID, ARG_CURRENT_DATE);
  
  		RETURN 0;
  
  	EXCEPTION
  	    WHEN NO_DATA_FOUND THEN
          RETURN 3;
  
  	END;
  /
  