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

<cfscript>
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 {};
}

data = readJsonBody();
businessId = structKeyExists(data, "BusinessID") ? val(data.BusinessID) : 0;
userId = structKeyExists(data, "UserID") ? val(data.UserID) : 0;

if (businessId <= 0) {
  apiAbort({ "OK": false, "ERROR": "missing_business_id" });
}
if (userId <= 0) {
  apiAbort({ "OK": false, "ERROR": "missing_user_id" });
}

try {
  // Check if already exists
  qCheck = queryExecute("
    SELECT ID, IsActive FROM Employees
    WHERE BusinessID = ? AND UserID = ?
  ", [
    { value: businessId, cfsqltype: "cf_sql_integer" },
    { value: userId, cfsqltype: "cf_sql_integer" }
  ], { datasource: "payfrit" });

  if (qCheck.recordCount > 0) {
    // Update to active
    queryExecute("
      UPDATE Employees
      SET IsActive = 1, StatusID = 2
      WHERE BusinessID = ? AND UserID = ?
    ", [
      { value: businessId, cfsqltype: "cf_sql_integer" },
      { value: userId, cfsqltype: "cf_sql_integer" }
    ], { datasource: "payfrit" });
    apiAbort({ "OK": true, "MESSAGE": "Employee reactivated", "EmployeeID": qCheck.ID });
  }

  // Insert new
  // NOTE: BusinessID in Employees is technically redundant since
  // the business relationship is established via ServicePoint -> Beacon chain.
  // Kept for legacy/convenience but could be derived from context.
  queryExecute("
    INSERT INTO Employees (BusinessID, UserID, StatusID, IsActive)
    VALUES (?, ?, 2, 1)
  ", [
    { value: businessId, cfsqltype: "cf_sql_integer" },
    { value: userId, cfsqltype: "cf_sql_integer" }
  ], { datasource: "payfrit" });

  qNew = queryExecute("SELECT LAST_INSERT_ID() AS EmployeeID", {}, { datasource: "payfrit" });

  apiAbort({ "OK": true, "MESSAGE": "Team member added", "EmployeeID": qNew.ID });

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