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

<cfscript>
// Seed default task categories for a business
// Input: BusinessID (required)
// Output: { OK: true, CATEGORIES: [...] }

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();

    // Get BusinessID from URL, body, or header
    businessID = 0;
    httpHeaders = getHttpRequestData().headers;

    if (structKeyExists(url, "bid") && isNumeric(url.bid)) {
        businessID = int(url.bid);
    } else if (structKeyExists(url, "BusinessID") && isNumeric(url.BusinessID)) {
        businessID = int(url.BusinessID);
    } else if (structKeyExists(data, "BusinessID") && isNumeric(data.BusinessID)) {
        businessID = int(data.BusinessID);
    } else if (structKeyExists(httpHeaders, "X-Business-ID") && isNumeric(httpHeaders["X-Business-ID"])) {
        businessID = int(httpHeaders["X-Business-ID"]);
    }

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

    // Check if categories already exist
    qCheck = queryExecute("
        SELECT COUNT(*) AS cnt FROM TaskCategories
        WHERE BusinessID = :businessID
    ", {
        businessID: { value: businessID, cfsqltype: "cf_sql_integer" }
    }, { datasource: "payfrit" });

    if (qCheck.cnt > 0) {
        // Categories already exist, just return them
        qCategories = queryExecute("
            SELECT ID, Name, Color
            FROM TaskCategories
            WHERE BusinessID = :businessID AND IsActive = 1
            ORDER BY Name
        ", {
            businessID: { value: businessID, cfsqltype: "cf_sql_integer" }
        }, { datasource: "payfrit" });

        categories = [];
        for (row in qCategories) {
            arrayAppend(categories, {
                "TaskCategoryID": row.ID,
                "Name": row.Name,
                "Color": row.Color
            });
        }

        apiAbort({
            "OK": true,
            "MESSAGE": "Categories already exist",
            "CATEGORIES": categories
        });
    }

    // Default categories for restaurants
    defaults = [
        { name: "Service Point", color: "##F44336" },      // Red - for service point requests
        { name: "Kitchen", color: "##FF9800" },            // Orange
        { name: "Bar", color: "##9C27B0" },                // Purple
        { name: "Cleaning", color: "##4CAF50" },           // Green
        { name: "Management", color: "##2196F3" },         // Blue
        { name: "Delivery", color: "##00BCD4" },           // Cyan
        { name: "General", color: "##607D8B" }             // Blue Grey
    ];

    // Insert defaults
    for (cat in defaults) {
        queryExecute("
            INSERT INTO TaskCategories (BusinessID, Name, Color)
            VALUES (:businessID, :name, :color)
        ", {
            businessID: { value: businessID, cfsqltype: "cf_sql_integer" },
            name: { value: cat.name, cfsqltype: "cf_sql_varchar" },
            color: { value: cat.color, cfsqltype: "cf_sql_varchar" }
        }, { datasource: "payfrit" });
    }

    // Return the created categories
    qCategories = queryExecute("
        SELECT ID, Name, Color
        FROM TaskCategories
        WHERE BusinessID = :businessID AND IsActive = 1
        ORDER BY Name
    ", {
        businessID: { value: businessID, cfsqltype: "cf_sql_integer" }
    }, { datasource: "payfrit" });

    categories = [];
    for (row in qCategories) {
        arrayAppend(categories, {
            "TaskCategoryID": row.ID,
            "Name": row.Name,
            "Color": row.Color
        });
    }

    apiAbort({
        "OK": true,
        "MESSAGE": "Created " & arrayLen(defaults) & " default categories",
        "CATEGORIES": categories
    });

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