// ============================================================================
// ЗАЯВКИ v2 — клієнтський API-шар. Звертається до /api/requests (SQLite на бекенді).
// Мапить записи з бекенду у форму, яку чекають прототипні компоненти (ageMin/ts/type-ключ).
// Глобалі через window (файл — окремий babel-скрипт, як решта CRM).
// ============================================================================

const LS_TYPE_KEYS = new Set(["product", "warranty", "return", "question", "docs", "mgrq"]);
// Старі лейбли зі старого листа → нові ключі (даних мало, best-effort).
const LS_TYPE_FROM_LABEL = {
  "Запит товару": "product", "Гарантія": "warranty", "Повернення": "return",
  "Питання": "question", "Документи": "docs", "Документ": "docs", "Менеджери": "mgrq",
};

function lsShortTs(ms) {
  if (!ms) return "";
  const d = new Date(ms), now = new Date();
  if (d.toDateString() === now.toDateString())
    return d.toLocaleTimeString("uk-UA", { hour: "2-digit", minute: "2-digit" });
  const y = new Date(now); y.setDate(now.getDate() - 1);
  if (d.toDateString() === y.toDateString()) return "Вчора";
  return d.toLocaleDateString("uk-UA", { day: "2-digit", month: "2-digit" });
}

// Запис із бекенду → форма для прототипних компонентів.
function lsMapRecord(r) {
  const ageMin = r.createdAt ? Math.max(0, Math.floor((Date.now() - r.createdAt) / 60000)) : 0;
  const type = LS_TYPE_KEYS.has(r.type) ? r.type : (LS_TYPE_FROM_LABEL[r.type] || r.type);
  return { ...r, type, ageMin, ts: r.createdAt ? lsShortTs(r.createdAt) : (r.date || "") };
}

async function lsJson(url, opts) {
  const r = await fetch(url, opts);
  let j = {}; try { j = await r.json(); } catch {}
  if (!r.ok) throw new Error(j.error || ("HTTP " + r.status));
  return j;
}
const lsJsonBody = (obj) => ({ headers: { "Content-Type": "application/json" }, body: JSON.stringify(obj) });

const lsApi = {
  async list() {
    const j = await lsJson("/api/requests");
    return (j.requests || []).map(lsMapRecord);
  },
  create(body)          { return lsJson("/api/requests", { method: "POST", ...lsJsonBody(body) }); },
  update(id, patch)     { return lsJson("/api/requests/" + id, { method: "PUT", ...lsJsonBody(patch) }); },
  status(id, status)    { return lsJson("/api/requests/" + id + "/status", { method: "PATCH", ...lsJsonBody({ status }) }); },
  remove(id)            { return lsJson("/api/requests/" + id, { method: "DELETE" }); },
  uploadFile(id, file)  { return lsJson("/api/requests/" + id + "/file", { method: "POST", ...lsJsonBody(file) }); }, // file: {name,mime,dataB64}
  async files(id)       { const j = await lsJson("/api/requests/" + id + "/files"); return j.files || []; },          // збережені файли заявки
  deleteFile(fileId)    { return lsJson("/api/requests/file/" + fileId, { method: "DELETE" }); },
  // Переглянути/скачати файл: <a href> не несе Authorization → тягнемо blob через fetch
  async openFile(fileId) {
    const r = await fetch("/api/requests/file/" + fileId);
    if (!r.ok) { let j = {}; try { j = await r.json(); } catch {} throw new Error(j.error === "file expired" ? "Файл прострочений (зберігаємо ~3 дні)" : (j.error || "HTTP " + r.status)); }
    const blob = await r.blob();
    window.open(URL.createObjectURL(blob), "_blank");
  },
  async managers()      { try { const j = await lsJson("/api/managers"); return j.managers || []; } catch { return []; } },
  // Пошук замовлення для авто-заповнення (гарантія/повернення): { orderId } або { phone }
  orderLookup({ orderId, phone }) {
    const q = orderId ? "orderId=" + encodeURIComponent(orderId) : "phone=" + encodeURIComponent(phone);
    return lsJson("/api/requests/order-lookup?" + q);
  },
  // Уточнити наявність (через бота). peek=true — миттєвий погляд у прайс БЕЗ пінга постачальнику.
  checkAvail(article, managerName, requestId, peek) {
    return lsJson("/api/requests/check-availability", { method: "POST", ...lsJsonBody({ article, managerName, requestId, peek }) });
  },
  // ТТН від наших ФОПів (лише власник)
  async npSenders()   { const j = await lsJson("/api/np/senders"); return j.senders || []; },
  npPreviewTtn(body)  { return lsJson("/api/np/ttn/preview", { method: "POST", ...lsJsonBody(body) }); },
  npCreateTtn(body)   { return lsJson("/api/np/ttn", { method: "POST", ...lsJsonBody(body) }); },
  // Пошук рахунків у базі (для прикріплення в документи): за № замовлення або № рахунку
  async searchInvoices({ orderId, no }) {
    const q = orderId != null && orderId !== "" ? "orderId=" + encodeURIComponent(orderId) : "no=" + encodeURIComponent(no);
    const j = await lsJson("/api/invoices?" + q);
    return j.invoices || [];
  },
  // Переглянути/скачати PDF рахунку за invoiceId+kind (стабільне посилання)
  async openInvoiceFile(invoiceId, kind) {
    const r = await fetch("/api/invoices/" + invoiceId + "/file/" + kind);
    if (!r.ok) { let j = {}; try { j = await r.json(); } catch {} throw new Error(j.error === "file expired" ? "Файл прострочений (рахунки зберігаємо ~60 днів)" : (j.error || "HTTP " + r.status)); }
    window.open(URL.createObjectURL(await r.blob()), "_blank");
  },
};

// Пошук товару в каталозі сайту (для форми заявки): [{article,name,price,currency,presence}]
async function lsCatalogSearch(q) {
  try { const j = await lsJson("/api/catalog/search?q=" + encodeURIComponent(q)); return j.products || []; } catch { return []; }
}
// Нова Пошта — автокомпліт міст/відділень (reuse ендпоінтів із замовлень)
async function lsNpCities(q) {
  try { const a = await lsJson("/api/np/cities?q=" + encodeURIComponent(q)); return (a || []).map(x => ({ label: x.Present, value: x.MainDescription || x.Present })); } catch { return []; }
}
async function lsNpWarehouses(city, q) {
  try { const d = await lsJson("/api/np/warehouses?cityName=" + encodeURIComponent(city || "") + "&q=" + encodeURIComponent(q || "")); return (d || []).map(w => ({ label: w.Description, value: w.Description })); } catch { return []; }
}
// Вулиці міста (адресна доставка) — сервер сам резолвить CityRef за назвою міста
async function lsNpStreets(city, q) {
  try { const d = await lsJson("/api/np/streets?cityName=" + encodeURIComponent(city || "") + "&q=" + encodeURIComponent(q || "")); return (d || []).map(s => ({ label: ((s.StreetsType || "") + " " + s.Description).trim(), value: s.Description })); } catch { return []; }
}

Object.assign(window, { lsApi, lsMapRecord, lsShortTs, LS_TYPE_KEYS, lsCatalogSearch, lsNpCities, lsNpWarehouses, lsNpStreets });
