/// @ts-check

onRecordAfterCreateSuccess((e) => {
  const APP_ID = "524cb6d8-2640-4f85-bb24-c9c762233de7";
  const API_KEY = "os_v2_app_kjglnwbgibhylozezhdweiz546iv5ns5h2hujfvrsao64p7qkqk6lwqthgwirm6naxdy37tmd5nivppfqmxrnqreoewpgqkcnawjjpy";
  try {
    const rec = e.record;
    if (rec.getString("status") !== "pending") return;
    const labTenantId = rec.getString("lab_tenant_id");
    const code = rec.getString("patient_code") || "Is";
    const type = rec.getString("prosthetic_type") || "";
    const label = type ? code + " - " + type : code;
    const jobId = rec.getString("id");
    let userIds = [];
    try {
      const members = $app.findRecordsByFilter("tenant_members", 'tenant_id = "' + labTenantId + '"', "", 100, 0);
      userIds = members.map(function(r) { return r.getString("user_id"); }).filter(Boolean);
    } catch (_) {}
    if (!userIds.length) return;
    const res = $http.send({
      url: "https://onesignal.com/api/v1/notifications",
      method: "POST",
      headers: { "Content-Type": "application/json", "Authorization": "Basic " + API_KEY },
      body: JSON.stringify({ app_id: APP_ID, include_external_user_ids: userIds, channel_for_external_user_ids: "push",
        headings: { en: "Yeni Is Talebi", tr: "Yeni Is Talebi" },
        contents: { en: label + " icin yeni bir is talebi geldi.", tr: label + " icin yeni bir is talebi geldi." },
        data: { job_id: jobId, tenant_type: "lab" } }),
      timeout: 10,
    });
    console.log("[notif-create] status=" + res.statusCode + " users=" + userIds.length);
  } catch (err) {
    console.log("[notif-create] error: " + String(err));
  }
}, "jobs");

onRecordAfterUpdateSuccess((e) => {
  const APP_ID = "524cb6d8-2640-4f85-bb24-c9c762233de7";
  const API_KEY = "os_v2_app_kjglnwbgibhylozezhdweiz546iv5ns5h2hujfvrsao64p7qkqk6lwqthgwirm6naxdy37tmd5nivppfqmxrnqreoewpgqkcnawjjpy";
  try {
    const rec = e.record;
    const newStatus      = rec.getString("status");
    const newLocation    = rec.getString("location");
    const clinicTenantId = rec.getString("clinic_tenant_id");
    const labTenantId    = rec.getString("lab_tenant_id");
    const code = rec.getString("patient_code") || "Is";
    const type = rec.getString("prosthetic_type") || "";
    const label = type ? code + " - " + type : code;
    const jobId = rec.getString("id");
    let oldStatus = "";
    let oldLocation = "";
    try {
      const orig = rec.original();
      if (orig) {
        oldStatus   = orig.getString("status");
        oldLocation = orig.getString("location");
      }
    } catch (_) {}

    if (oldStatus && oldStatus === newStatus && oldLocation === newLocation) return;

    let targetTenantId = "";
    let title = "";
    let body = "";
    let tenantType = "clinic";

    if (oldStatus === "pending" && newStatus === "in_progress" && newLocation === "at_lab") {
      targetTenantId = clinicTenantId; title = "Is Kabul Edildi";
      body = label + " laboratuvar tarafindan kabul edildi."; tenantType = "clinic";
    } else if (newStatus === "in_progress" && newLocation === "at_clinic" && oldLocation !== "at_clinic") {
      targetTenantId = clinicTenantId; title = "Prova Onayi Bekleniyor";
      body = label + " prova icin klinik onayini bekliyor."; tenantType = "clinic";
    } else if (oldLocation === "at_clinic" && newLocation === "at_lab" && newStatus === "in_progress") {
      targetTenantId = labTenantId; title = "Klinik Geri Bildirimi";
      body = label + " icin klinikten geri bildirim geldi."; tenantType = "lab";
    } else if (newStatus === "sent" && oldStatus !== "sent") {
      targetTenantId = clinicTenantId; title = "Teslimat Hazir";
      body = label + " teslim icin hazir."; tenantType = "clinic";
    } else if (newStatus === "delivered" && oldStatus !== "delivered") {
      targetTenantId = labTenantId; title = "Is Teslim Alindi";
      body = label + " klinik tarafindan teslim alindi."; tenantType = "lab";
    } else if (newStatus === "cancelled" && oldStatus !== "cancelled") {
      let allIds = [];
      try {
        const cm = $app.findRecordsByFilter("tenant_members", 'tenant_id = "' + clinicTenantId + '"', "", 100, 0);
        const lm = $app.findRecordsByFilter("tenant_members", 'tenant_id = "' + labTenantId + '"', "", 100, 0);
        const raw = cm.concat(lm).map(function(r) { return r.getString("user_id"); }).filter(Boolean);
        allIds = raw.filter(function(id, idx) { return raw.indexOf(id) === idx; });
      } catch (_) {}
      if (!allIds.length) return;
      const res = $http.send({
        url: "https://onesignal.com/api/v1/notifications",
        method: "POST",
        headers: { "Content-Type": "application/json", "Authorization": "Basic " + API_KEY },
        body: JSON.stringify({ app_id: APP_ID, include_external_user_ids: allIds, channel_for_external_user_ids: "push",
          headings: { en: "Is Iptal Edildi", tr: "Is Iptal Edildi" },
          contents: { en: label + " iptal edildi.", tr: label + " iptal edildi." },
          data: { job_id: jobId, tenant_type: "clinic" } }),
        timeout: 10,
      });
      console.log("[notif-update] cancelled status=" + res.statusCode + " users=" + allIds.length);
      return;
    } else {
      return;
    }

    let userIds = [];
    try {
      const members = $app.findRecordsByFilter("tenant_members", 'tenant_id = "' + targetTenantId + '"', "", 100, 0);
      userIds = members.map(function(r) { return r.getString("user_id"); }).filter(Boolean);
    } catch (_) {}

    if (!userIds.length) return;

    const res = $http.send({
      url: "https://onesignal.com/api/v1/notifications",
      method: "POST",
      headers: { "Content-Type": "application/json", "Authorization": "Basic " + API_KEY },
      body: JSON.stringify({ app_id: APP_ID, include_external_user_ids: userIds, channel_for_external_user_ids: "push",
        headings: { en: title, tr: title },
        contents: { en: body, tr: body },
        data: { job_id: jobId, tenant_type: tenantType } }),
      timeout: 10,
    });
    console.log("[notif-update] " + title + " status=" + res.statusCode + " users=" + userIds.length);

  } catch (err) {
    console.log("[notif-update] error: " + String(err));
  }
}, "jobs");
