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

<cfscript>
/**
 * Create or reuse Stripe Connect Express account for worker.
 */

response = { "OK": false };

try {
    requestData = deserializeJSON(toString(getHttpRequestData().content));
    userID = val(requestData.UserID ?: 0);

    if (userID == 0 && structKeyExists(request, "UserID")) {
        userID = val(request.UserID);
    }

    if (userID == 0) {
        response["ERROR"] = "missing_params";
        response["MESSAGE"] = "UserID is required.";
        writeOutput(serializeJSON(response));
        abort;
    }

    qUser = queryTimed("
        SELECT StripeConnectedAccountID, EmailAddress, FirstName, LastName
        FROM Users WHERE ID = :userID
    ", { userID: userID }, { datasource: "payfrit" });

    if (qUser.recordCount == 0) {
        response["ERROR"] = "user_not_found";
        writeOutput(serializeJSON(response));
        abort;
    }

    existingAccountID = qUser.StripeConnectedAccountID ?: "";

    if (len(trim(existingAccountID)) > 0) {
        // Already has an account
        response["OK"] = true;
        response["ACCOUNT_ID"] = existingAccountID;
        response["CREATED"] = false;
        writeOutput(serializeJSON(response));
        abort;
    }

    // Create new Stripe Connect Express account
    stripeSecretKey = application.stripeSecretKey ?: "";

    httpService = new http();
    httpService.setMethod("POST");
    httpService.setUrl("https://api.stripe.com/v1/accounts");
    httpService.setUsername(stripeSecretKey);
    httpService.setPassword("");

    httpService.addParam(type="formfield", name="type", value="express");
    httpService.addParam(type="formfield", name="country", value="US");

    userEmail = qUser.EmailAddress ?: "";
    if (len(trim(userEmail)) > 0) {
        httpService.addParam(type="formfield", name="email", value=userEmail);
    }

    httpService.addParam(type="formfield", name="capabilities[transfers][requested]", value="true");
    httpService.addParam(type="formfield", name="metadata[user_id]", value=userID);

    result = httpService.send().getPrefix();
    acctData = deserializeJSON(result.fileContent);

    if (structKeyExists(acctData, "error")) {
        response["ERROR"] = acctData.error.message;
        writeOutput(serializeJSON(response));
        abort;
    }

    newAccountID = acctData.id;

    // Save to Users table
    queryTimed("
        UPDATE Users SET StripeConnectedAccountID = :acctID WHERE ID = :userID
    ", { acctID: newAccountID, userID: userID }, { datasource: "payfrit" });

    response["OK"] = true;
    response["ACCOUNT_ID"] = newAccountID;
    response["CREATED"] = true;

} catch (any e) {
    response["ERROR"] = e.message;
}

writeOutput(serializeJSON(response));
</cfscript>
