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

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

businessID = val(data.BusinessID ?: 0);
role = lcase(trim(data.Role ?: "owner")); // "owner" or "guest"
statusFilter = structKeyExists(data, "StatusFilter") ? val(data.StatusFilter) : -1; // -1 = all

if (businessID LTE 0) {
    // Fall back to request.BusinessID
    businessID = val(structKeyExists(request, "BusinessID") ? request.BusinessID : 0);
}
if (businessID LTE 0) {
    apiAbort({ "OK": false, "ERROR": "missing_businessid", "MESSAGE": "BusinessID is required." });
}

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

// Build WHERE clause based on role
if (role == "guest") {
    whereClause = "g.GuestBusinessID = :bizId";
} else {
    whereClause = "g.OwnerBusinessID = :bizId";
}

statusClause = "";
if (statusFilter >= 0) {
    statusClause = " AND g.StatusID = :statusFilter";
}

sql = "
    SELECT
        g.ID AS GrantID,
        g.UUID,
        g.OwnerBusinessID,
        g.GuestBusinessID,
        g.ServicePointID,
        g.StatusID,
        g.EconomicsType,
        g.EconomicsValue,
        g.EligibilityScope,
        g.TimePolicyType,
        g.TimePolicyData,
        g.CreatedOn,
        g.AcceptedOn,
        g.RevokedOn,
        ob.Name AS OwnerBusinessName,
        gb.Name AS GuestBusinessName,
        sp.Name AS ServicePointName,
        sp.TypeID AS ServicePointTypeID
    FROM ServicePointGrants g
    JOIN Businesses ob ON ob.ID = g.OwnerBusinessID
    JOIN Businesses gb ON gb.ID = g.GuestBusinessID
    JOIN ServicePoints sp ON sp.ID = g.ServicePointID
    WHERE #whereClause##statusClause#
    ORDER BY g.CreatedOn DESC
    LIMIT 200
";

params = { bizId: { value = businessID, cfsqltype = "cf_sql_integer" } };
if (statusFilter >= 0) {
    params.statusFilter = { value = statusFilter, cfsqltype = "cf_sql_integer" };
}

qGrants = queryTimed(sql, params, { datasource = "payfrit" });

grants = [];
for (row in qGrants) {
    arrayAppend(grants, {
        "GrantID": row.GrantID,
        "UUID": row.UUID,
        "OwnerBusinessID": row.OwnerBusinessID,
        "GuestBusinessID": row.GuestBusinessID,
        "ServicePointID": row.ServicePointID,
        "StatusID": row.StatusID,
        "EconomicsType": row.EconomicsType,
        "EconomicsValue": row.EconomicsValue,
        "EligibilityScope": row.EligibilityScope,
        "TimePolicyType": row.TimePolicyType,
        "TimePolicyData": row.TimePolicyData ?: "",
        "CreatedOn": row.CreatedOn,
        "AcceptedOn": row.AcceptedOn ?: "",
        "RevokedOn": row.RevokedOn ?: "",
        "OwnerBusinessName": row.OwnerBusinessName,
        "GuestBusinessName": row.GuestBusinessName,
        "ServicePointName": row.ServicePointName,
        "ServicePointTypeID": row.ServicePointTypeID
    });
}

writeOutput(serializeJSON({
    "OK": true,
    "Role": role,
    "BusinessID": businessID,
    "Count": arrayLen(grants),
    "Grants": grants
}));
</cfscript>
