#!/usr/bin/perl

$headers = `cat /opt/folio/config/headers`; chomp($headers);
$url = `cat /opt/folio/config/url`; chomp($url); 

use JSON;

$loansJ = `curl -s -X GET -G $headers -d 'limit=10000' $url/circulation/loans?query=itemEffectiveLocationIdAtCheckOut==d2c63f26-f7c8-4ce2-b849-33ba4ad08207`;
$loansH = decode_json $loansJ;
for ( @{$loansH->{loans}} ) {
	$statusName = $_->{status}->{name};
	if ($statusName eq "Closed") {
		$loanId = $_->{id};
		$itemId = $_->{item}->{id};
		$holdingsRecordId = $_->{item}->{holdingsRecordId};
		$instanceId = $_->{item}->{instanceId};
		$scheduledNoticesJ = `curl -s -X GET -G $headers $url/scheduled-notice-storage/scheduled-notices?query=loanId==$loanId`;
		$scheduledNoticesH = decode_json $scheduledNoticesJ;
		for ( @{$scheduledNoticesH->{scheduledNotices}} ) {
			$scheduledNoticeId = $_->{id};
			$scheduledNoticeD = `curl -s -X DELETE $headers $url/scheduled-notice-storage/scheduled-notices/$scheduledNoticeId`;
		}
		$requestsJ = `curl -s -X GET -G $headers $url/request-storage/requests?query=itemId==$itemId`;
		$requestsH = decode_json $requestsJ;
		for ( @{$requestsH->{requests}} ) {
			$requestId = $_->{id};
			$requestsD = `curl -s -X DELETE $headers $url/request-storage/requests/$requestId`;
		}
		$loanD = `curl -s -X DELETE $headers $url/circulation/loans/$loanId`;
		$itemD = `curl -s -X DELETE $headers $url/item-storage/items/$itemId`;
		$holdingsRecordD = `curl -s -X DELETE $headers $url/holdings-storage/holdings/$holdingsRecordId`;
		$instanceD = `curl -s -X DELETE $headers $url/instance-storage/instances/$instanceId`;
	}
}