// Lesson 5: a script Power Automate can call. Takes a region, returns its total.
function main(workbook: ExcelScript.Workbook, region: string): number {
  const table = workbook.getTable("Sales");
  if (!table) throw new Error("Table 'Sales' not found");
  const regions = table.getColumnByName("Region").getRangeBetweenHeaderAndTotal().getValues();
  const amounts = table.getColumnByName("Amount").getRangeBetweenHeaderAndTotal().getValues();
  let total = 0;
  regions.forEach((r, i) => { if (r[0] === region) total += Number(amounts[i][0]); });
  workbook.getWorksheet("Summary")?.getRange("B1").setValue(total);
  return total;
}
