<cfsetting showdebugoutput="false">
<cfsetting enablecfoutputonly="true">
<cfcontent type="application/json; charset=utf-8" reset="true">
<cfheader name="Cache-Control" value="no-store">

<cfscript>
data = {};
try {
    raw = toString(getHttpRequestData().content);
    if (len(trim(raw))) {
        data = deserializeJSON(raw);
        if (!isStruct(data)) data = {};
    }
} catch (any e) { data = {}; }

query = trim(data.Query ?: "");
excludeBusinessID = val(data.ExcludeBusinessID ?: 0);

if (len(query) < 2) {
    apiAbort({ "OK": false, "ERROR": "query_too_short", "MESSAGE": "Search query must be at least 2 characters." });
}

// Search by name or ID
params = {};
sql = "SELECT ID, Name FROM Businesses WHERE 1=1";

if (isNumeric(query)) {
    sql &= " AND ID = :bizId";
    params.bizId = { value = int(query), cfsqltype = "cf_sql_integer" };
} else {
    sql &= " AND Name LIKE :namePattern";
    params.namePattern = { value = "%" & query & "%", cfsqltype = "cf_sql_varchar" };
}

if (excludeBusinessID GT 0) {
    sql &= " AND ID != :excludeId";
    params.excludeId = { value = excludeBusinessID, cfsqltype = "cf_sql_integer" };
}

sql &= " ORDER BY Name LIMIT 20";

qResults = queryTimed(sql, params, { datasource = "payfrit" });

businesses = [];
for (row in qResults) {
    arrayAppend(businesses, {
        "BusinessID": row.ID,
        "Name": row.Name
    });
}

writeOutput(serializeJSON({
    "OK": true,
    "Count": arrayLen(businesses),
    "Businesses": businesses
}));
</cfscript>
