async function addItemsToList(siteUrl, listName, items) {
  if (!Array.isArray(items) || items.length === 0) {
    throw new Error("Items must be a non-empty array of objects.");
  }

  // Get FormDigestValue
  const digestResponse = await fetch(`${siteUrl}/_api/contextinfo`, {
    method: "POST",
    headers: { Accept: "application/json;odata=verbose" },
  });
  const digestData = await digestResponse.json();
  const requestDigest = digestData.d.GetContextWebInformation.FormDigestValue;

  // Get List Item Entity Type
  const typeResponse = await fetch(
    `${siteUrl}/_api/web/lists/getbytitle('${listName}')?$select=ListItemEntityTypeFullName`,
    { headers: { Accept: "application/json;odata=verbose" } }
  );
  const typeData = await typeResponse.json();
  const entityType = typeData.d.ListItemEntityTypeFullName;

  const listEndpoint = `${siteUrl}/_api/web/lists/getbytitle('${listName}')/items`;
  const results = [];

  for (const item of items) {
    const payload = { ...item, __metadata: { type: entityType } };

    const response = await fetch(listEndpoint, {
      method: "POST",
      headers: {
        Accept: "application/json;odata=verbose",
        "Content-Type": "application/json;odata=verbose",
        "X-RequestDigest": requestDigest,
      },
      body: JSON.stringify(payload),
    });

    if (!response.ok) {
      const errText = await response.text();
      throw new Error(`Failed to add item: ${response.status} – ${errText}`);
    }

    const data = await response.json();
    results.push(data.d);
  }

  return results;
}

// Example usage:
(async () => {
  const siteUrl = "https://portal.mapnamd2.com/HRM/meetings";
  const listName = "meetings";
  const items = [
    { Title: "Project A", Status: "Active" },
    { Title: "Project B", Status: "Completed" },
  ];

  try {
    const addedItems = await addItemsToList(siteUrl, listName, items);
    console.log("✅ Items added:", addedItems);
  } catch (err) {
    console.error("❌ Error:", err);
  }
})();
