/***********************************************************************************************
COST IMPORT
/**********************************************************************************************/
var config_spreadsheet_url = "config spreadsheet url";
var sheet_name = "cost_import";
var notification_email = "test@email.cz";
var api_version = "v2";
/***********************************************************************************************
Script:      Cost Import
Version:     28.4.2026
Created By:  Stanislav Jilek (cost-import.cz)
/**********************************************************************************************/

function main() {
  //!Do not delete, necessary for authorisation
  //UrlFetchApp.fetch();
  //SpreadsheetApp.openByUrl();
  //MailApp.sendEmail();
  //DriveApp.Folder.createFile();
  //BigQuery.Tables.get();

  var domains = ["cz", "sk", "com"].sort(() => Math.random() - 0.5);
  var options = { "method": "post", "payload": { "function": "main" } };

  for (var i = 0; i < 2; i++) {
    for (var j = 0; j < domains.length; j++) {
      var url = "https://www.cost-import." + domains[j] + "/api/" + api_version + "/";
      try {
        var response = UrlFetchApp.fetch(url, options);
        var run = new Function("config_spreadsheet_url", "sheet_name", response.getContentText());
        run(config_spreadsheet_url, sheet_name);
        return;
      } catch (err) {
        Utilities.sleep(2000);
      }
    }
  }

  var subject = "Cost Import - Error";
  var message = "Spouštěcí skript se nepřipojil k API.";

  MailApp.sendEmail(notification_email, subject, message);
  Logger.log(message);
}