<cfsetting showdebugoutput="false">
<cfsetting enablecfoutputonly="true">
<cfcontent type="application/json; charset=utf-8" reset="true">
<cfheader name="Cache-Control" value="no-store">

<cfinclude template="_grantUtils.cfm">

<cfscript>
data = {};
try {
    raw = toString(getHttpRequestData().content);
    if (len(trim(raw))) {
        data = deserializeJSON(raw);
        if (!isStruct(data)) data = {};
    }
} catch (any e) { data = {}; }

grantID = val(data.GrantID ?: 0);
if (grantID LTE 0) {
    apiAbort({ "OK": false, "ERROR": "missing_grantid", "MESSAGE": "GrantID is required." });
}

callerUserID = val(structKeyExists(request, "UserID") ? request.UserID : 0);
if (callerUserID LTE 0) {
    apiAbort({ "OK": false, "ERROR": "not_authenticated" });
}

qGrant = queryTimed(
    "SELECT g.*, b.UserID AS GuestOwnerUserID
     FROM ServicePointGrants g
     JOIN Businesses b ON b.ID = g.GuestBusinessID
     WHERE g.ID = ?
     LIMIT 1",
    [{ value = grantID, cfsqltype = "cf_sql_integer" }],
    { datasource = "payfrit" }
);

if (qGrant.recordCount == 0) {
    apiAbort({ "OK": false, "ERROR": "not_found", "MESSAGE": "Grant not found." });
}

if (qGrant.GuestOwnerUserID != callerUserID) {
    apiAbort({ "OK": false, "ERROR": "not_guest_owner", "MESSAGE": "Only the guest business owner can decline this invite." });
}

if (qGrant.StatusID != 0) {
    apiAbort({ "OK": false, "ERROR": "bad_state", "MESSAGE": "Only pending grants can be declined." });
}

queryTimed(
    "UPDATE ServicePointGrants SET StatusID = 2 WHERE ID = ?",
    [{ value = grantID, cfsqltype = "cf_sql_integer" }],
    { datasource = "payfrit" }
);

recordGrantHistory(
    grantID = grantID,
    action = "declined",
    actorUserID = callerUserID,
    actorBusinessID = qGrant.GuestBusinessID,
    previousData = { "StatusID": 0 },
    newData = { "StatusID": 2 }
);

writeOutput(serializeJSON({
    "OK": true,
    "GrantID": grantID,
    "MESSAGE": "Grant declined."
}));
</cfscript>
