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

<cfcontent type="application/json; charset=utf-8" reset="true">
<cfheader name="Cache-Control" value="public, max-age=3600">

<!---
GetShardPool API
================
Returns the complete list of active shard UUIDs.
Used by apps for remote config to get updated UUID pool.

Request:
  GET /api/beacon-sharding/get_shard_pool.cfm
  GET /api/beacon-sharding/get_shard_pool.cfm?since=10  (only shards added after ID 10)

Response:
  {
    "OK": true,
    "Version": 1,
    "Count": 64,
    "Shards": [
      { "ID": 1, "UUID": "f7826da6-4fa2-4e98-8024-bc5b71e0893e" },
      ...
    ]
  }

Notes:
  - This is a PUBLIC endpoint - no auth required
  - Append-only: never remove UUIDs, only add new ones
  - Apps should cache locally and only fetch new shards periodically
  - Use "since" param to only get newly added shards
--->

<cftry>
<cfscript>
sinceId = 0;
if (structKeyExists(url, "since") && isNumeric(url.since) && url.since GT 0) {
  sinceId = int(url.since);
}
</cfscript>

<cfquery name="qShards" datasource="payfrit">
  SELECT ID, UUID
  FROM BeaconShards
  WHERE IsActive = 1
  <cfif sinceId GT 0>
    AND ID > <cfqueryparam cfsqltype="cf_sql_integer" value="#sinceId#">
  </cfif>
  ORDER BY ID ASC
</cfquery>

<cfset shards = []>
<cfset maxId = 0>
<cfloop query="qShards">
  <cfset arrayAppend(shards, {
    "ID" = qShards.ID,
    "UUID" = qShards.UUID
  })>
  <cfif qShards.ID GT maxId>
    <cfset maxId = qShards.ID>
  </cfif>
</cfloop>

<cfoutput>#serializeJSON({
  OK = true,
  Version = maxId,
  Count = arrayLen(shards),
  Shards = shards
})#</cfoutput>

<cfcatch type="any">
  <cfheader statuscode="200" statustext="OK">
  <cfcontent type="application/json; charset=utf-8" reset="true">
  <cfoutput>#serializeJSON({ OK=false, ERROR="server_error", MESSAGE=cfcatch.message })#</cfoutput>
</cfcatch>
</cftry>
