// API layer — calls our Express backend
const API = {
  async get(path) {
    const res = await fetch(path);
    const data = await res.json();
    if (!res.ok) throw new Error(data.error || `HTTP ${res.status}`);
    return data;
  },
  async post(path, body) {
    const res = await fetch(path, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(body),
    });
    const data = await res.json();
    if (!res.ok) throw new Error(data.error || `HTTP ${res.status}`);
    return data;
  },

  async getOrders() {
    return API.get("/api/orders");
  },

  async setOrderStatus(orderId, statusId) {
    return API.post(`/api/orders/${orderId}/status`, { status_id: statusId });
  },

  async setPaymentType(orderId, paymentTypeId, userId) {
    return API.post(`/api/orders/${orderId}/payment`, { payment_type_id: paymentTypeId, user_id: userId });
  },

  async getOrder(orderId) {
    return API.get(`/api/orders/${orderId}`);
  },

  async getSupplierStatuses() {
    return API.get('/api/supplier-status');
  },

  async setAttributes(orderId, fields, userId) {
    return API.post(`/api/orders/${orderId}/attributes`, { fields, user_id: userId });
  },

  async login(username, password) {
    return API.post("/api/login", { username, password });
  },

  async searchNPCities(q) {
    return API.get(`/api/np/cities?q=${encodeURIComponent(q)}`);
  },
  async searchNPWarehouses(cityName, q) {
    return API.get(`/api/np/warehouses?cityName=${encodeURIComponent(cityName)}&q=${encodeURIComponent(q)}`);
  },
  async searchNPStreets(cityRef, q) {
    return API.get(`/api/np/streets?cityRef=${encodeURIComponent(cityRef)}&q=${encodeURIComponent(q)}`);
  },
  async findHoroshopCities(term, orderId, userId) {
    return API.post('/api/horoshop/cities', { term, orderId, userId });
  },
  async setDeliveryType(orderId, deliveryTypeId, userId) {
    return API.post(`/api/orders/${orderId}/delivery-type`, { delivery_type_id: deliveryTypeId, user_id: userId });
  },

  async getCalls(force = false) {
    return API.get(`/api/calls${force ? '?force=1' : ''}`);
  },

  async getRequests() {
    return API.get('/api/requests');
  },
  async createRequest(data) {
    return API.post('/api/requests', data);
  },
  async updateRequest(id, data) {
    const res = await fetch(`/api/requests/${id}`, {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(data),
    });
    const json = await res.json();
    if (!res.ok) throw new Error(json.error || `HTTP ${res.status}`);
    return json;
  },
  async searchOrdersByPhone(phone) {
    return API.get(`/api/orders/by-phone?phone=${encodeURIComponent(phone)}`);
  },
  async checkAvailability(article, managerName, requestId) {
    return API.post('/api/requests/check-availability', { article, managerName, requestId });
  },
};

// Map Horoshop API order to our display format
function mapOrder(o) {
  const statusKey = HOROSHOP_STATUS_MAP[o._status] || "new";
  const address = [o.delivery_city_stable, o.delivery_address].filter(Boolean).join(", ");
  const products = (o.products || []).map(p => p.title);
  const productsRaw = o.products || [];

  const comments = [];
  if (o.manager_comment) {
    comments.push({ author: "Менеджер", date: "", text: o.manager_comment });
  }

  const dd = Array.isArray(o.delivery_data) ? o.delivery_data[0] : o.delivery_data;
  const ttn = dd ? {
    id:           dd.tnID || null,
    number:       dd.tnNumber || null,
    status:       dd.tnStatusName || null,
    updatedAt:    dd.tnTrackingUpdateDate || null,
    deliveryDate: dd.estimatedDeliveryDate || null,
  } : null;

  return {
    id:            o.order_id,
    client:        o.delivery_name || "—",
    phone:         o.delivery_phone || "—",
    messengers:    [],
    products,
    productsRaw,
    address,
    delivery:      o.delivery_type?.title || "—",
    deliveryPrice: o.delivery_price,
    payment:       o.payment_type?.title || "—",
    payed:         o.payed,
    totalDefault:  o.total_default || 0,
    paymentPrice:  o.payment_price || 0,
    total:         (o.total_default || 0) + (o.payment_price || 0),
    status:        statusKey,
    statusId:      o.status,
    userId:        o.user,
    created:       fmtDate(o.stat_created),
    createdRaw:    o.stat_created,
    comment:       o.comment || "",
    managerComment:o.manager_comment || "",
    comments,
    city:          o.delivery_city_stable || "",
    email:         o.delivery_email || "",
    withoutCallback: o.order_without_callback,
    ttn,
  };
}

window.API = API;
window.mapOrder = mapOrder;
