module analytics.api;

import handy_http_primitives;
import profile.data;
import profile.service;

void handleGetBalanceTimeSeries(ref ServerHttpRequest request, ref ServerHttpResponse response) {
    auto ds = getProfileDataSource(request);
    serveJsonFromProperty(response, ds, "analytics.balanceTimeSeries");
}

/**
 * Helper method to serve JSON analytics data to a client by fetching it
 * directly from the user's profile properties table and writing it to the
 * response.
 * Params:
 *   response = The response to write to.
 *   ds = The datasource to serve data from.
 *   key = The name of the analytics property to read data from.
 */
private void serveJsonFromProperty(ref ServerHttpResponse response, ref ProfileDataSource ds, string key) {
    PropertiesRepository propsRepo = ds.getPropertiesRepository();
    string jsonStr = propsRepo.findProperty(key).orElse(null);
    if (jsonStr is null || jsonStr.length == 0) {
        response.status = HttpStatus.NOT_FOUND;
        response.writeBodyString("No data found for " ~ key);
    } else {
        response.writeBodyString(jsonStr, ContentTypes.APPLICATION_JSON);
    }
}
