<cfsetting showdebugoutput="false">
<cfsetting enablecfoutputonly="true">
<cfcontent type="application/json; charset=utf-8">

<cfscript>
function apiAbort(payload) {
  writeOutput(serializeJSON(payload));
  abort;
}

// Resolve BusinessID tolerant MVP way
bizId = 0;

if (structKeyExists(request, "BusinessID") && isNumeric(request.BusinessID)) {
  bizId = int(request.BusinessID);
}

if (bizId LTE 0) {
  try {
    raw = toString(getHttpRequestData().content);
    if (len(trim(raw))) {
      body = deserializeJSON(raw);
      if (isStruct(body) && structKeyExists(body, "BusinessID") && isNumeric(body.BusinessID)) {
        bizId = int(body.BusinessID);
      }
    }
  } catch (any e) {}
}

if (bizId LTE 0 && structKeyExists(url, "BusinessID") && isNumeric(url.BusinessID)) {
  bizId = int(url.BusinessID);
}

if (bizId LTE 0) {
  apiAbort({ "OK": false, "ERROR": "missing_businessid", "DETAIL": "" });
}

try {
  // Detect the correct business FK column in ServicePoints
  qCols = queryExecute(
    "
      SELECT COLUMN_NAME
      FROM INFORMATION_SCHEMA.COLUMNS
      WHERE TABLE_SCHEMA = DATABASE()
        AND TABLE_NAME = 'ServicePoints'
    ",
    [],
    { datasource: "payfrit" }
  );

  cols = [];
  for (r in qCols) arrayAppend(cols, r.COLUMN_NAME);

  // Candidates in preferred order (add more if needed)
  candidates = [
    "BusinessID",
    "BusinessId",
    "ServicePointBusinessID",
    "ServicePointsBusinessID",
    "Business_ID",
    "Business",
    "BusinessFk",
    "BusinessFK"
  ];

  bizCol = "";
  // First: exact candidate match
  for (c in candidates) {
    for (colName in cols) {
      if (lcase(colName) EQ lcase(c)) {
        bizCol = colName;
        break;
      }
    }
    if (len(bizCol)) break;
  }

  // Second: heuristic: any column containing "business" and "id"
  if (!len(bizCol)) {
    for (colName in cols) {
      if (findNoCase("business", colName) && findNoCase("id", colName)) {
        bizCol = colName;
        break;
      }
    }
  }

  if (!len(bizCol)) {
    apiAbort({
      "OK": false,
      "ERROR": "schema_mismatch",
      "DETAIL": "Could not find a BusinessID-like column in ServicePoints. Available columns: " & arrayToList(cols, ", ")
    });
  }

  // Build SQL using detected column name (safe because it comes from INFORMATION_SCHEMA)
  sql = "
    SELECT
      ServicePointID,
      ServicePointName
    FROM ServicePoints
    WHERE #bizCol# = ?
    ORDER BY ServicePointName
  ";

  q = queryExecute(
    sql,
    [ { value: bizId, cfsqltype: "cf_sql_integer" } ],
    { datasource: "payfrit" }
  );

  servicePoints = [];
  for (row in q) {
    arrayAppend(servicePoints, {
      "ServicePointID": row.ServicePointID,
      "ServicePointName": row.ServicePointName
    });
  }

  writeOutput(serializeJSON({
    "OK": true,
    "ERROR": "",
    "DETAIL": "",
    "BusinessID": bizId,
    "BusinessColumn": bizCol,
    "COUNT": arrayLen(servicePoints),
    "ServicePoints": servicePoints
  }));
} catch (any e) {
  apiAbort({
    "OK": false,
    "ERROR": "db_error",
    "DETAIL": e.message
  });
}
</cfscript>
