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

<cfscript>
response = { "OK": false };

try {
    requestBody = toString(getHttpRequestData().content);
    requestData = {};
    if (len(requestBody)) {
        requestData = deserializeJSON(requestBody);
    }

    confirmDelete = requestData.confirm ?: "";

    if (confirmDelete != "NUKE_EVERYTHING") {
        throw("Must pass confirm: 'NUKE_EVERYTHING' to proceed");
    }

    // Get counts before deletion
    qItemCount = queryTimed("SELECT COUNT(*) as cnt FROM Items", {}, { datasource: "payfrit" });
    qCatCount = queryTimed("SELECT COUNT(*) as cnt FROM Categories", {}, { datasource: "payfrit" });
    qLinkCount = queryTimed("SELECT COUNT(*) as cnt FROM lt_ItemID_TemplateItemID", {}, { datasource: "payfrit" });

    // Delete in correct order (foreign key constraints)
    queryTimed("DELETE FROM lt_ItemID_TemplateItemID", {}, { datasource: "payfrit" });
    queryTimed("DELETE FROM Items", {}, { datasource: "payfrit" });
    queryTimed("DELETE FROM Categories", {}, { datasource: "payfrit" });

    response = {
        "OK": true,
        "deleted": {
            "items": qItemCount.cnt,
            "categories": qCatCount.cnt,
            "templateLinks": qLinkCount.cnt
        }
    };

} catch (any e) {
    response = {
        "OK": false,
        "ERROR": e.message,
        "DETAIL": e.detail ?: ""
    };
}

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