<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>

<cftry>
  <!--- Disable foreign key checks temporarily --->
  <cfset queryTimed("SET FOREIGN_KEY_CHECKS = 0", [], { datasource = "payfrit" })>

  <!--- Clear Tasks --->
  <cfset queryTimed("DELETE FROM Tasks", [], { datasource = "payfrit" })>

  <!--- Clear Payments --->
  <cftry>
    <cfset queryTimed("DELETE FROM Payments", [], { datasource = "payfrit" })>
    <cfcatch></cfcatch>
  </cftry>

  <!--- Clear OrderLineItemModifiers if exists --->
  <cftry>
    <cfset queryTimed("DELETE FROM OrderLineItemModifiers", [], { datasource = "payfrit" })>
    <cfcatch></cfcatch>
  </cftry>

  <!--- Clear OrderLineItems --->
  <cfset queryTimed("DELETE FROM OrderLineItems", [], { datasource = "payfrit" })>

  <!--- Clear Orders --->
  <cfset queryTimed("DELETE FROM Orders", [], { datasource = "payfrit" })>

  <!--- Re-enable foreign key checks --->
  <cfset queryTimed("SET FOREIGN_KEY_CHECKS = 1", [], { datasource = "payfrit" })>

  <!--- Reset auto-increment counters --->
  <cfset queryTimed("ALTER TABLE Tasks AUTO_INCREMENT = 1", [], { datasource = "payfrit" })>
  <cfset queryTimed("ALTER TABLE Orders AUTO_INCREMENT = 1", [], { datasource = "payfrit" })>
  <cfset queryTimed("ALTER TABLE OrderLineItems AUTO_INCREMENT = 1", [], { datasource = "payfrit" })>

  <cfset apiAbort({
    "OK": true,
    "MESSAGE": "All test data cleared successfully. Orders, OrderLineItems, and Tasks tables have been reset."
  })>

  <cfcatch>
    <cfset apiAbort({
      "OK": false,
      "ERROR": "reset_failed",
      "MESSAGE": cfcatch.message,
      "DETAIL": cfcatch.detail
    })>
  </cfcatch>
</cftry>
