<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){
    apiAbort({OK=false,ERROR="missing_body"});
  }
  try {
    parsed = deserializeJSON(raw);
  } catch(any e){
    apiAbort({OK=false,ERROR="bad_json",MESSAGE="Invalid JSON body"});
  }
  if (!isStruct(parsed)){
    apiAbort({OK=false,ERROR="bad_json",MESSAGE="JSON must be an object"});
  }
  return parsed;
}

function normStr(v){
  if (isNull(v)) return "";
  return trim(toString(v));
}

/* ---------- AUTH CONTEXT ---------- */
if (!structKeyExists(request,"UserID") || !isNumeric(request.UserID) || request.UserID LTE 0){
  apiAbort({OK=false,ERROR="not_logged_in"});
}
if (!structKeyExists(request,"BusinessID") || !isNumeric(request.BusinessID) || request.BusinessID LTE 0){
  apiAbort({OK=false,ERROR="no_business_selected"});
}

/* ---------- INPUT ---------- */
data = readJsonBody();

if (!structKeyExists(data,"BeaconID") || !isNumeric(data.BeaconID) || int(data.BeaconID) LTE 0){
  apiAbort({OK=false,ERROR="missing_BeaconID"});
}
if (!structKeyExists(data,"ServicePointID") || !isNumeric(data.ServicePointID) || int(data.ServicePointID) LTE 0){
  apiAbort({OK=false,ERROR="missing_ServicePointID"});
}

BeaconID = int(data.BeaconID);
ServicePointID = int(data.ServicePointID);
Notes = "";
if (structKeyExists(data,"Notes")){
  Notes = left(normStr(data.Notes), 255);
}
</cfscript>

<!--- Validate Beacon belongs to Business --->
<cfquery name="qB" datasource="#application.datasource#">
  SELECT BeaconID
  FROM Beacons
  WHERE BeaconID = <cfqueryparam cfsqltype="cf_sql_integer" value="#BeaconID#">
    AND BusinessID = <cfqueryparam cfsqltype="cf_sql_integer" value="#request.BusinessID#">
  LIMIT 1
</cfquery>
<cfif qB.recordCount EQ 0>
  <cfoutput>#serializeJSON({OK=false,ERROR="beacon_not_found_for_business"})#</cfoutput>
  <cfabort>
</cfif>

<!--- Validate ServicePoint belongs to Business --->
<cfquery name="qS" datasource="#application.datasource#">
  SELECT ServicePointID
  FROM ServicePoints
  WHERE ServicePointID = <cfqueryparam cfsqltype="cf_sql_integer" value="#ServicePointID#">
    AND BusinessID = <cfqueryparam cfsqltype="cf_sql_integer" value="#request.BusinessID#">
  LIMIT 1
</cfquery>
<cfif qS.recordCount EQ 0>
  <cfoutput>#serializeJSON({OK=false,ERROR="servicepoint_not_found_for_business"})#</cfoutput>
  <cfabort>
</cfif>

<!--- Enforce 1:1 uniqueness --->
<cfquery name="qBeaconTaken" datasource="#application.datasource#">
  SELECT lt_Beacon_Businesses_ServicePointID
  FROM lt_Beacon_Businesses_ServicePoints
  WHERE BusinessID = <cfqueryparam cfsqltype="cf_sql_integer" value="#request.BusinessID#">
    AND BeaconID = <cfqueryparam cfsqltype="cf_sql_integer" value="#BeaconID#">
  LIMIT 1
</cfquery>
<cfif qBeaconTaken.recordCount GT 0>
  <cfoutput>#serializeJSON({OK=false,ERROR="beacon_already_assigned"})#</cfoutput>
  <cfabort>
</cfif>

<cfquery name="qServicePointTaken" datasource="#application.datasource#">
  SELECT lt_Beacon_Businesses_ServicePointID
  FROM lt_Beacon_Businesses_ServicePoints
  WHERE BusinessID = <cfqueryparam cfsqltype="cf_sql_integer" value="#request.BusinessID#">
    AND ServicePointID = <cfqueryparam cfsqltype="cf_sql_integer" value="#ServicePointID#">
  LIMIT 1
</cfquery>
<cfif qServicePointTaken.recordCount GT 0>
  <cfoutput>#serializeJSON({OK=false,ERROR="servicepoint_already_assigned"})#</cfoutput>
  <cfabort>
</cfif>

<!--- INSERT --->
<cfquery datasource="#application.datasource#">
  INSERT INTO lt_Beacon_Businesses_ServicePoints
    (BusinessID, BeaconID, ServicePointID,
     lt_Beacon_Businesses_ServicePointAssignedByUserID,
     lt_Beacon_Businesses_ServicePointNotes)
  VALUES
    (
      <cfqueryparam cfsqltype="cf_sql_integer" value="#request.BusinessID#">,
      <cfqueryparam cfsqltype="cf_sql_integer" value="#BeaconID#">,
      <cfqueryparam cfsqltype="cf_sql_integer" value="#ServicePointID#">,
      <cfqueryparam cfsqltype="cf_sql_integer" value="#request.UserID#">,
      <cfqueryparam cfsqltype="cf_sql_varchar" value="#Notes#" null="#(len(Notes) EQ 0)#">
    )
</cfquery>

<cfquery name="qID" datasource="#application.datasource#">
  SELECT LAST_INSERT_ID() AS NewID
</cfquery>

<cfoutput>#serializeJSON({
  "OK"=true,
  "ACTION"="inserted",
  "lt_Beacon_Businesses_ServicePointID"=qID.NewID,
  "BeaconID"=BeaconID,
  "ServicePointID"=ServicePointID,
  "BusinessID"=(request.BusinessID & "")
})#</cfoutput>
