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

<cfscript>
/**
 * Check for duplicate businesses
 *
 * POST JSON:
 * {
 *   "name": "Business Name",
 *   "addressLine1": "123 Main St",
 *   "city": "Los Angeles",
 *   "state": "CA",
 *   "zip": "90001"
 * }
 *
 * Returns:
 * {
 *   "OK": true,
 *   "duplicates": [ { BusinessID, Name, Address } ]
 * }
 */

response = { "OK": true, "duplicates": [] };

try {
    requestBody = toString(getHttpRequestData().content);
    if (!len(requestBody)) {
        throw(message="No request body provided");
    }

    data = deserializeJSON(requestBody);

    bizName = structKeyExists(data, "name") && isSimpleValue(data.name) ? trim(data.name) : "";
    addressLine1 = structKeyExists(data, "addressLine1") && isSimpleValue(data.addressLine1) ? trim(data.addressLine1) : "";
    city = structKeyExists(data, "city") && isSimpleValue(data.city) ? trim(data.city) : "";
    state = structKeyExists(data, "state") && isSimpleValue(data.state) ? trim(data.state) : "";
    zip = structKeyExists(data, "zip") && isSimpleValue(data.zip) ? trim(data.zip) : "";

    // Clean up city - remove trailing punctuation
    city = reReplace(city, "[,.\s]+$", "", "all");

    // Build query to find potential duplicates
    // Match by name (case-insensitive) OR by address components
    qDuplicates = queryTimed("
        SELECT DISTINCT
            b.ID AS BusinessID,
            b.Name AS Name,
            a.Line1,
            a.City,
            s.Abbreviation as AddressState,
            a.ZIPCode
        FROM Businesses b
        LEFT JOIN Addresses a ON a.BusinessID = b.ID
        LEFT JOIN tt_States s ON s.ID = a.StateID
        WHERE
            LOWER(b.Name) = LOWER(:bizName)
            OR (
                LOWER(a.Line1) = LOWER(:addressLine1)
                AND LOWER(a.City) = LOWER(:city)
                AND a.Line1 != ''
                AND a.City != ''
            )
        ORDER BY b.Name
    ", {
        bizName: bizName,
        addressLine1: addressLine1,
        city: city
    }, { datasource: "payfrit" });

    for (i = 1; i <= qDuplicates.recordCount; i++) {
        addressParts = [];
        if (len(qDuplicates.Line1[i])) arrayAppend(addressParts, qDuplicates.Line1[i]);
        if (len(qDuplicates.City[i])) arrayAppend(addressParts, qDuplicates.City[i]);
        if (len(qDuplicates.AddressState[i])) arrayAppend(addressParts, qDuplicates.AddressState[i]);
        if (len(qDuplicates.ZIPCode[i])) arrayAppend(addressParts, qDuplicates.ZIPCode[i]);

        arrayAppend(response.duplicates, {
            "BusinessID": qDuplicates.BusinessID[i],
            "Name": qDuplicates.Name[i],
            "Address": arrayToList(addressParts, ", ")
        });
    }

} catch (any e) {
    response.OK = false;
    response.error = e.message;
}

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