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

<cffunction name="apiAbort" access="public" returntype="void" output="true">
  <cfargument name="payload" type="struct" required="true">
  <cfcontent type="application/json; charset=utf-8">
  <cfoutput>#serializeJSON(arguments.payload)#</cfoutput>
  <cfabort>
</cffunction>

<cffunction name="readJsonBody" access="public" returntype="struct" output="false">
  <cfset var raw = getHttpRequestData().content>
  <cfif isNull(raw) OR len(trim(raw)) EQ 0>
    <cfreturn {}>
  </cfif>
  <cftry>
    <cfset var data = deserializeJSON(raw)>
    <cfif isStruct(data)>
      <cfreturn data>
    <cfelse>
      <cfreturn {}>
    </cfif>
    <cfcatch>
      <cfreturn {}>
    </cfcatch>
  </cftry>
</cffunction>

<cfset data = readJsonBody()>
<cfset TaskID = val( structKeyExists(data,"TaskID") ? data.TaskID : 0 )>
<cfset UserID = val( structKeyExists(request,"UserID") ? request.UserID : 0 )>

<cfif TaskID LTE 0>
  <cfset apiAbort({ "OK": false, "ERROR": "missing_params", "MESSAGE": "TaskID is required." })>
</cfif>

<cftry>
  <!--- Verify task exists and is unclaimed --->
  <cfset qTask = queryTimed("
    SELECT ID, ClaimedByUserID, BusinessID, OrderID
    FROM Tasks
    WHERE ID = ?
  ", [ { value = TaskID, cfsqltype = "cf_sql_integer" } ], { datasource = "payfrit" })>

  <cfif qTask.recordCount EQ 0>
    <cfset apiAbort({ "OK": false, "ERROR": "not_found", "MESSAGE": "Task not found." })>
  </cfif>

  <cfif qTask.ClaimedByUserID GT 0>
    <cfset apiAbort({ "OK": false, "ERROR": "already_accepted", "MESSAGE": "Task has already been claimed." })>
  </cfif>

  <!--- Update task to claimed --->
  <cfset queryTimed("
    UPDATE Tasks
    SET ClaimedByUserID = ?,
        ClaimedOn = NOW()
    WHERE ID = ?
      AND ClaimedByUserID = 0
  ", [
    { value = UserID GT 0 ? UserID : 1, cfsqltype = "cf_sql_integer" },
    { value = TaskID, cfsqltype = "cf_sql_integer" }
  ], { datasource = "payfrit" })>

  <!--- NOTE: Do NOT update order status when accepting/claiming task --->
  <!--- Order should remain at status 3 (Order complete, final prep) until task is completed --->
  <!--- When task is completed, order status will be updated to 5 (Delivered) --->

  <cfset apiAbort({
    "OK": true,
    "ERROR": "",
    "MESSAGE": "Task claimed successfully.",
    "TaskID": TaskID
  })>

  <cfcatch>
    <cfset apiAbort({
      "OK": false,
      "ERROR": "server_error",
      "MESSAGE": "Error claiming task",
      "DETAIL": cfcatch.message
    })>
  </cfcatch>
</cftry>
