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

<!--- Set an address as the default delivery address --->
<cfscript>
function readJsonBody() {
    var raw = getHttpRequestData().content;
    if (isNull(raw) || len(trim(toString(raw))) == 0) return {};
    try {
        var data = deserializeJSON(toString(raw));
        return isStruct(data) ? data : {};
    } catch (any e) {
        return {};
    }
}

try {
    userId = request.UserID ?: 0;

    if (userId <= 0) {
        writeOutput(serializeJSON({
            "OK": false,
            "ERROR": "unauthorized",
            "MESSAGE": "Authentication required"
        }));
        abort;
    }

    data = readJsonBody();
    addressId = val(data.AddressID ?: 0);

    if (addressId <= 0) {
        writeOutput(serializeJSON({
            "OK": false,
            "ERROR": "missing_field",
            "MESSAGE": "AddressID is required"
        }));
        abort;
    }

    // Verify address belongs to user
    qCheck = queryExecute("
        SELECT AddressID
        FROM Addresses
        WHERE AddressID = :addressId
          AND AddressUserID = :userId
          AND AddressIsDeleted = 0
    ", {
        addressId: { value: addressId, cfsqltype: "cf_sql_integer" },
        userId: { value: userId, cfsqltype: "cf_sql_integer" }
    }, { datasource: "payfrit" });

    if (qCheck.recordCount == 0) {
        writeOutput(serializeJSON({
            "OK": false,
            "ERROR": "not_found",
            "MESSAGE": "Address not found"
        }));
        abort;
    }

    // Clear all defaults for this user
    queryExecute("
        UPDATE Addresses
        SET AddressIsDefaultDelivery = 0
        WHERE AddressUserID = :userId
          AND (AddressBusinessID = 0 OR AddressBusinessID IS NULL)
          AND AddressTypeID LIKE '%2%'
    ", {
        userId: { value: userId, cfsqltype: "cf_sql_integer" }
    }, { datasource: "payfrit" });

    // Set this one as default
    queryExecute("
        UPDATE Addresses
        SET AddressIsDefaultDelivery = 1
        WHERE AddressID = :addressId
    ", {
        addressId: { value: addressId, cfsqltype: "cf_sql_integer" }
    }, { datasource: "payfrit" });

    writeOutput(serializeJSON({
        "OK": true,
        "MESSAGE": "Default address updated"
    }));

} catch (any e) {
    writeOutput(serializeJSON({
        "OK": false,
        "ERROR": "server_error",
        "MESSAGE": e.message
    }));
}
</cfscript>
