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

<cfscript>
/*
  FILE: C:\lucee\tomcat\webapps\ROOT\biz.payfrit.com\api\businesses\list.cfm

  MVP:
  - PUBLIC endpoint (no login required)
  - Returns a minimal list of restaurants/businesses for the drilldown.
  - IMPORTANT: Output JSON manually to preserve exact key casing.

  RESPONSE (case-sensitive keys):
  {
    "OK": true,
    "COUNT": 15,
    "Businesses": [
      { "BusinessID": 12, "BusinessName": "Annie's Soul Delicious" },
      ...
    ]
  }
*/

function apiAbort(obj) {
  writeOutput('{');
  writeOutput('"OK":' & (obj.OK ? 'true' : 'false'));

  if (structKeyExists(obj, "ERROR")) {
    writeOutput(',"ERROR":"' & encodeForJSON(toString(obj.ERROR)) & '"');
  }
  if (structKeyExists(obj, "DETAIL")) {
    writeOutput(',"DETAIL":"' & encodeForJSON(toString(obj.DETAIL)) & '"');
  }

  writeOutput('}');
  abort;
}

// NOTE: Do NOT use 'var' at top-level in a .cfm (local scope is function-only).
dsn = "";
if (structKeyExists(request, "datasource") && len(trim(request.datasource))) {
  dsn = trim(request.datasource);
} else if (structKeyExists(request, "dsn") && len(trim(request.dsn))) {
  dsn = trim(request.dsn);
} else if (structKeyExists(application, "datasource") && len(trim(application.datasource))) {
  dsn = trim(application.datasource);
} else if (structKeyExists(application, "dsn") && len(trim(application.dsn))) {
  dsn = trim(application.dsn);
}

if (!len(dsn)) {
  apiAbort({
    OK=false,
    ERROR="missing_datasource",
    DETAIL="No datasource found in request.datasource, request.dsn, application.datasource, or application.dsn."
  });
}

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

countVal = q.recordCount;

writeOutput('{');
writeOutput('"OK":true');
writeOutput(',"COUNT":' & countVal);
writeOutput(',"Businesses":[');

for (i = 1; i LTE q.recordCount; i = i + 1) {
  if (i GT 1) writeOutput(',');

  bid = q["BusinessID"][i];
  bname = q["BusinessName"][i];

  writeOutput('{');
  writeOutput('"BusinessID":' & int(bid));
  writeOutput(',"BusinessName":"' & encodeForJSON(toString(bname)) & '"');
  writeOutput('}');
}

writeOutput(']}');
</cfscript>
