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

<cfscript>
// Mark messages as read
// Input: TaskID, ReaderType (customer/worker) - marks messages from the OTHER party as read
// Output: { OK: true }

function apiAbort(required struct payload) {
    writeOutput(serializeJSON(payload));
    abort;
}

function readJsonBody() {
    var raw = getHttpRequestData().content;
    if (isNull(raw)) raw = "";
    if (!len(trim(raw))) return {};
    try {
        var data = deserializeJSON(raw);
        if (isStruct(data)) return data;
    } catch (any e) {}
    return {};
}

try {
    data = readJsonBody();
    taskID = val(structKeyExists(data, "TaskID") ? data.TaskID : 0);
    readerType = lcase(trim(structKeyExists(data, "ReaderType") ? data.ReaderType : ""));

    if (taskID == 0) {
        apiAbort({ "OK": false, "ERROR": "missing_params", "MESSAGE": "TaskID is required" });
    }

    if (readerType != "customer" && readerType != "worker") {
        apiAbort({ "OK": false, "ERROR": "missing_params", "MESSAGE": "ReaderType must be 'customer' or 'worker'" });
    }

    // Mark messages from the OTHER party as read
    // If reader is customer, mark worker messages as read
    // If reader is worker, mark customer messages as read
    otherType = readerType == "customer" ? "worker" : "customer";

    queryExecute("
        UPDATE ChatMessages
        SET IsRead = 1
        WHERE TaskID = :taskID AND SenderType = :otherType AND IsRead = 0
    ", {
        taskID: { value: taskID, cfsqltype: "cf_sql_integer" },
        otherType: { value: otherType, cfsqltype: "cf_sql_varchar" }
    }, { datasource: "payfrit" });

    apiAbort({
        "OK": true,
        "MESSAGE": "Messages marked as read"
    });

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