<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(payload) {
  writeOutput(serializeJSON(payload));
  abort;
}

try {
  q = queryExecute(
    "
      SELECT
        BusinessID,
        BusinessName
      FROM Businesses
      ORDER BY BusinessName
    ",
    [],
    { datasource = "payfrit" }
  );

  // Convert query -> array of structs (JSON-native)
  rows = [];
  for (i = 1; i <= q.recordCount; i++) {
    arrayAppend(rows, {
      "BusinessID": q.BusinessID[i],
      "BusinessName": q.BusinessName[i]
    });
  }

  // Provide BOTH keys to satisfy any Flutter casing expectation
  writeOutput(serializeJSON({
    "OK": true,
    "ERROR": "",
    "VERSION": "businesses_list_v3",
    "BUSINESSES": rows,
    "Businesses": rows
  }));
  abort;

} catch (any e) {
  apiAbort({
    "OK": false,
    "ERROR": "server_error",
    "DETAIL": e.message
  });
}
</cfscript>
