<cfsetting showdebugoutput="false">
<cfsetting enablecfoutputonly="true">

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

<cfscript>
function apiAbort(obj) {
  writeOutput(serializeJSON(obj));
  abort;
}

function readJsonBody() {
  raw = toString(getHttpRequestData().content);
  if (isNull(raw) || len(trim(raw)) EQ 0) return {};
  try {
    parsed = deserializeJSON(raw);
  } catch(any e) {
    apiAbort({ OK=false, ERROR="bad_json", MESSAGE="Invalid JSON body" });
  }
  if (!isStruct(parsed)) return {};
  return parsed;
}

data = readJsonBody();

if (!structKeyExists(data, "BeaconID") || !isNumeric(data.BeaconID) || int(data.BeaconID) LTE 0) {
  apiAbort({ OK=false, ERROR="missing_beacon_id", MESSAGE="BeaconID is required" });
}

beaconId = int(data.BeaconID);
</cfscript>

<cfquery name="qAssignment" datasource="payfrit">
  SELECT
    lt.BusinessID,
    lt.BeaconID,
    lt.ServicePointID,
    b.BeaconName,
    b.BeaconUUID,
    b.BeaconIsActive,
    biz.BusinessName,
    sp.ServicePointName,
    sp.ServicePointIsActive
  FROM lt_Beacon_Businesses_ServicePoints lt
  INNER JOIN Beacons b ON b.BeaconID = lt.BeaconID
  INNER JOIN Businesses biz ON biz.BusinessID = lt.BusinessID
  INNER JOIN ServicePoints sp ON sp.ServicePointID = lt.ServicePointID
  WHERE lt.BeaconID = <cfqueryparam cfsqltype="cf_sql_integer" value="#beaconId#">
    AND b.BeaconIsActive = 1
    AND sp.ServicePointIsActive = b'1'
  LIMIT 1
</cfquery>

<cfif qAssignment.recordCount EQ 0>
  <cfoutput>#serializeJSON({ OK=false, ERROR="not_found", MESSAGE="Beacon not found, inactive, or not assigned to an active service point" })#</cfoutput>
  <cfabort>
</cfif>

<cfset response = {
  "OK" = true,
  "ERROR" = "",
  "BEACON" = {
    "BeaconID" = qAssignment.BeaconID,
    "BeaconName" = qAssignment.BeaconName,
    "UUID" = qAssignment.BeaconUUID
  },
  "BUSINESS" = {
    "BusinessID" = qAssignment.BusinessID,
    "BusinessName" = qAssignment.BusinessName
  },
  "SERVICEPOINT" = {
    "ServicePointID" = qAssignment.ServicePointID,
    "ServicePointName" = qAssignment.ServicePointName,
    "ServicePointIsActive" = qAssignment.ServicePointIsActive
  }
}>

<cfoutput>#serializeJSON(response)#</cfoutput>
